Invalid model when using petapoco and editortemplates

263 views Asked by At

I am using Petapoco (in Umbraco) to fetch an IEnumerable from the DB and pass it to the view. Code below abbreviated for easy overview
Model:

public class Account  
{  
    [Column("accountId")]
    [PrimaryKeyColumn(AutoIncrement = true)]
    [HiddenInput(DisplayValue = false)]
    public int accountId { get; set; }

    [Column("accountCode")]
    [Required(ErrorMessage = "Enter the account code (max 20 chars)")]
    [Display(Name = "Account code")]
    public string accountCode { get; set; }
}

Controller:

   var db = ApplicationContext.DatabaseContext.Database;
   var all = db.Query<Account>("SELECT * FROM account");
   return PartialView("_accountList", all);

Partial view:

@model IEnumerable<App.Models.AccountListViewModel>

//notice I manually set the template name because MVC does not see this as an  
//'Account' model but a 'Umbraco.Core.Persistence.Database+<Query>d__7`1[App.Models.Account]'
//model
@Html.EditorForModel("Account") 

Editor template:

@model App.Models.Account

<div>
   <p>account code<br/>
   @Html.TextBoxFor(x => x.accountCode, new { @class = "form-control input-sm" })
   </p>
   @Html.HiddenFor(a => a.accountId)
</div>

When running above I get the following error:

System.InvalidOperationException: The model item passed into the dictionary is of type 'Umbraco.Core.Persistence.Database+d__7`1[App.Models.Account]', but this dictionary requires a model item of type 'App.Models.Account'.

How can I get the editor template to see this a an Account model? Or is it a constraint in PetaPoco to use the editor templates? Yet it is strange that the view accepts the model as Account but the editor template does not.

Any help is appreciated!

1

There are 1 answers

3
Eduardo Molteni On

In your Partial View your model is an IEnumerable, but later in your editor template you have only one object.

Should be:

@model IEnumerable<App.Models.AccountListViewModel>

@foreach (var item in Model ) {
   Html.EditorFor(item) 
}