我在控制器中有这个代码
Expression<Func<Title, bool>> filterExpr = null;
Func<IQueryable<Title>, IOrderedQueryable<Title>> orderByFunc = null;
List<Title> titles = unitOfWork.TitleRepository.Get(filter: filterExpr, orderBy: orderByFunc, includeProperties: "").ToList();
return View("Index", titles);
这是模型
public partial class Title
{
public Title()
{
this.NumberTitles = new HashSet<NumberTitle>();
this.Title1 = new HashSet<Title>();
}
public int Id { get; set; }
public string TitleText { get; set; }
public Nullable<int> TitleId { get; set; }
public virtual ICollection<NumberTitle> NumberTitles { get; set; }
public virtual ICollection<Title> Title1 { get; set; }
public virtual Title Title2 { get; set; }
}
这是视图
@model IEnumerable<CinemavaadabiatModel.Title>
<table>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.TitleText)
</td>
</tr>
}
</table>
当我运行它时,我收到以下错误
传递到字典中的模型项的类型为'System.Collections.Generic.List 1[Project.Title]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
1 [Project.Title]'。
我的问题在哪里?
答案 0 :(得分:0)
您将存储库获取方法的结果转换为列表,然后再将其返回到视图中。您可以将视图中的模型类型更改为List<CinemavaadabiatModel.Title>
,也可以将控制器操作更改为不.ToList()
方法上的unitOfWork.TitleRepository.Get
(假设它返回IEnumerable
):
Expression<Func<Title, bool>> filterExpr = null;
Func<IQueryable<Title>, IOrderedQueryable<Title>> orderByFunc = null;
var titles = unitOfWork.TitleRepository.Get(filter: filterExpr,
orderBy: orderByFunc, includeProperties: "");
return View("Index", titles);
看起来好像它会返回IQueryable
,所以您最好将此IQueryable
个域模型转换为可以使用的IEnumerable
个视图模型在视图中,从而将域和表示层关注点分开。
<强>更新强>
作为替代方案,您可以创建TitleViewModel
并将标题添加到其中:
public class TitleViewModel
{
public TitleViewModel()
{
this.Titles = new List<CinemavaadabiatModel.Title>();
}
public IEnumerable<CinemavaadabiatModel.Title> Titles { get; set; }
}
然后您的控制器代码变为:
Expression<Func<Title, bool>> filterExpr = null;
Func<IQueryable<Title>, IOrderedQueryable<Title>> orderByFunc = null;
var titles = unitOfWork.TitleRepository.Get(filter: filterExpr,
orderBy: orderByFunc, includeProperties: "");
// consider using some kind of factory to create your ViewModel
// if unit testing is a concern
var viewModel = new TitleViewModel { Titles = titles.AsEnumerable() };
return View("Index", viewModel);
你的观点变成了:
@model TitleViewModel
<table>
@foreach (var item in Model.Titles) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.TitleText)
</td>
</tr>
}
</table>