Reputation: 487
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")
Upvotes: 1
Views: 10119
Reputation: 663
In my case, I overcame this type of error by following the below syntax of code, changed to the question scenario for clarification.
Public ActionResult ListClubMembershipType(int clubId)
{
List<MembershipTypeViewModel> types = db.MembershipTypes.Where(s=>s.ClubId ==
clubId).OrderBy(s=>s.Type).ToList();
return View(types);
}
In scenario's where you need to find only single Member out of Many:
List<MembershipTypeViewModel> types = db.MembershipTypes.Where(s=>s.ClubId ==
clubId).Take(1).ToList();
Upvotes: 0
Reputation: 1137
What you're trying to pass to the view and the view model are 2 different types, cast the entity bing brought from the database to an object of type :
ListMembershipTypeViewModel
You trying to pass it a List of MembershipTypes
Upvotes: 0
Reputation:
Your query is passing List<MembershipType>
to the view, but the view expects IEnumerable<ListMembershipTypeViewModel>
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 ListMembershipTypeViewModel
{
Type = t.Type,
ClubId = clubId
});
return View(model);
}
Side note: Your method should not include the parameter ListMembershipTypeViewModel model
Upvotes: 1