0

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!

tereško
  • 58,060
  • 25
  • 98
  • 150
lape
  • 41
  • 6

1 Answers1

0

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) 
}
Eduardo Molteni
  • 38,786
  • 23
  • 141
  • 206
  • Thanks Eduardo. As I am hearing MVC, the EditorForModel will automatically iterate the list and apply the EditorTemplate for each instance in the model, right? I think the issue is the name of the model coming from PetaPoco. I hope to be able to cast it somehow – lape Nov 21 '14 at 19:29
  • No, it does not automatically iterate the list. You can do an editor template for the list, but the you have to iterate the list there – Eduardo Molteni Nov 21 '14 at 19:35
  • Please see [this post](http://stackoverflow.com/questions/5700558/how-can-i-bind-nested-viewmodels-from-view-to-controller-in-mvc3). That refers to a nested List<> which is iterated through an EditorTemplate. Can't I do that here even though I have an IEnumerable<>? – lape Nov 22 '14 at 13:47