在 asp.net 上有一个应用程序。我决定为任何涉及它的模型编写一个接口和一个从它继承的排序类。一切通常都会得到一个排序的模型,但是当我试图在视图中吐出它时,问题就开始了。界面:
public interface IModelSort<T> where T : class
{
IEnumerable<T> GetModelSort(IEnumerable<T> model, Func<T, dynamic> predSort, string typeSort);
}
继承自该接口的类:
public class ModelSort<T> : IModelSort<T> where T : class
{
public IEnumerable<T> GetModelSort(IEnumerable<T> model, Func<T, dynamic> predSort, string typeSort = "Asc")
{
if (typeSort == "Asc")
return model.OrderBy(predSort);
else
return model.OrderByDescending(predSort);
}
}
接下来,我有一个名为 UnitOfBusiness 的类,它创建所有业务逻辑类的实例,包括这个:
public class UnitOfBusiness
{
private ModelSort<dynamic> modelSorting;
public ModelSort<dynamic> ModelSorting
{
get
{
if (modelSorting == null)
modelSorting = new ModelSort<dynamic>();
return modelSorting;
}
}
}
控制器:
public ActionResult Index(string sort, int page = 1)
{
IEnumerable<Car> cars = unitOfWOrk.Cars.GetAll();
var result = unitOfBusiness.ModelSorting.GetModelSort(cars, i => i.Price).ToList();
return View(result);
}
最后查看:
@model PagedList.IPagedList<AutoStore.Domain.Core.Car>
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
<h1>Каталог автомобилей</h1>
<style>
html,
body {
height: 100%;
}
body {
display: -ms-flexbox;
display: flex;
-ms-flex-align: center;
padding-top: 40px;
padding-bottom: 40px;
}
</style>
<table class="table table-bordered">
<thead>
<tr>
<th>
@Html.ActionLink("Марка", "Index")
</th>
<th>Модель</th>
<th>
@Html.ActionLink("Цена", "Index")
</th>
<th>Количество на складе</th>
</tr>
</thead>
<tbody>
@foreach (var item in ViewBag.Cars as List<AutoStore.Domain.Core.Car>)
{
<tr>
<td>@Html.DisplayFor(i => item.Mark.MarkName)</td>
<td>@Html.DisplayFor(i => item.CarModel.ModelName)</td>
<td>@Html.DisplayFor(i => item.Price)</td>
<td>@Html.DisplayFor(i => item.Count)</td>
</tr>
}
</tbody>
</table>
结果,视图出现错误:
传入字典的模型项的类型为“System.Collections.Generic.List
1[System.Object]', but this dictionary requires a model item of type 'PagedList.IPagedList1[AutoStore.Domain.Core.Car]”。
我尝试使用
result.ToPagedList(page, 8)
结果相同。我试图从错误中获益,并将其放在页面列表中的视图上,而不是模型、对象上,然后另一个错误发生了。
对象引用不指向对象的实例。
如果您通过 ViewBag 传递已排序的机器列表,则会发生同样的错误。请告诉我可以做什么?我已经伤透了脑筋。
删除动态
你的大华银行
控制器
PS我写在拖鞋上,整理在脑海里,这只是一个例子,说明如何摆脱动态