C# – The model item passed into the dictionary is of type , but this dictionary requires a model item of type ‘System.Collections.Generic.IEnumerable

asp.net-mvcc

I'm getting the following error when trying to view my index view:

The model item passed into the dictionary is of type 'System.Collections.Generic.List1[GRCWebApp.Models.MembershipType]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[GRCWebApp.ViewModels.ListMembershipTypeViewModel]'.

The Controller is:

        public ActionResult ListClubMembershipType(ListMembershipTypeViewModel model, int clubId)
    {
        var types = from s in db.MembershipTypes
                    where (s.ClubId == clubId)
                    orderby s.Type
                    select s;
        return View(types.ToList());
    }

And the view model is:

    public class ListMembershipTypeViewModel
{
    [Display(Name = "Type")]
    public String Type { get; set; }

    public int ClubId { get; set; }
}

The view is:

@model IEnumerable<GRCWebApp.ViewModels.ListMembershipTypeViewModel>

@{
ViewBag.Title = "Club Membership Types";
}

<h2>Club Membership Types</h2>

<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Type)
    </th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Type)
    </td>
</tr>
}

</table>

@Html.Partial("AddClubMembershipType")

Best Answer

Your query is passing List<MembershipType> to the view, but the view expects IEnumerable<ListMembershipTyp‌​eViewModel>

Change you GET method to

public ActionResult ListClubMembershipType(int clubId)
{

  var types = from s in db.MembershipTypes
              where (s.ClubId == clubId)
              orderby s.Type
              select s;
  var model = types.Select(t => new ListMembershipTyp‌​eViewModel
  {
    Type = t.Type,
    ClubId = clubId
  });
  return View(model);    
}

Side note: Your method should not include the parameter ListMembershipTypeViewModel model

Related Topic