简体   繁体   中英

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

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")

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

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM