我在尝试查看索引视图时遇到以下错误:
传递到字典中的模型项的类型为' System.Collections.Generic.List1 [GRCWebApp.Models.MembershipType]',但此字典需要类型为' System的模型项.Collections.Generic.IEnumerable1 [GRCWebApp.ViewModels.ListMembershipTypeViewModel]'
控制器是:
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());
}
视图模型是:
public class ListMembershipTypeViewModel
{
[Display(Name = "Type")]
public String Type { get; set; }
public int ClubId { get; set; }
}
观点是:
@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")
答案 0 :(得分:1)
您的查询正在将List<MembershipType>
传递给视图,但视图需要IEnumerable<ListMembershipTypeViewModel>
将GET方法更改为
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);
}
附注:您的方法不应包含参数ListMembershipTypeViewModel model
答案 1 :(得分:0)
您尝试传递给视图的内容和视图模型是两种不同的类型,将从数据库带来的实体bing转换为类型的对象:
ListMembershipTypeViewModel
您尝试将其传递给MembershipTypes列表
答案 2 :(得分:0)
对于我来说,我通过遵循以下代码语法克服了此类错误,将其更改为问题场景以进行澄清。
Public ActionResult ListClubMembershipType(int clubId)
{
List<MembershipTypeViewModel> types = db.MembershipTypes.Where(s=>s.ClubId ==
clubId).OrderBy(s=>s.Type).ToList();
return View(types);
}
在方案中,您只需从多个成员中查找单个成员:
List<MembershipTypeViewModel> types = db.MembershipTypes.Where(s=>s.ClubId ==
clubId).Take(1).ToList();