我正在创建一个过滤器 View 来查找记录。此示例位于 SO有帮助,但没有提及如何处理(已过滤)View
。
下面的错误是因为操作返回 List<ProductViewModel>
,并且它错误/提示 View 正在使用 SearchViewModel,
我需要这个POST
搜索模型/变量,但是 GET
返回列表/结果模型
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[ViewModels.ProductVM]', but this dictionary requires a model item of type 'ViewModels.SearchModel'.
问题:由于有两个模型,SearchViewModel
传递给 Controller & ProductViewModel
作为结果返回,哪个模型应该强类型化到 View ?以及如何创建 View 来处理 SearchModel
& ProductModel
如果我强类型 ProductVM,那么我会从 SearchVM 中释放提交表单。
我创建了 SearchView
作为主视图,& _ResultsPartialView
作为一个partialView,这是错误的吗?
public ActionResult Index(SearchModel searchModel)
{
var filteredProdVMList = _Repository.GetFilteredProducts(searchModel);
return View(filteredProdVMList);
}
public class ProductVM
{
public int Id { get; set; }
public int Price { get; set; }
public string Name { get; set; }
// implicit const... blah.. removed
}
public class SearchModel
{
public int? Id { get; set; }
public int? PriceFrom { get; set; }
public int? PriceTo { get; set; }
public string Name { get; set; }
}
最佳答案
您需要修改 SearchModel
以包含产品的集合属性
public class SearchModel
{
public int? PriceFrom { get; set; }
public int? PriceTo { get; set; }
....
public IEnumerable<ProductVM> Products { get; set; } // add
}
然后您只需将 SearchModel
返回到您的 View
public ActionResult Filter(SearchModel filter)
{
filter.Products = _repository.GetFilteredProducts(filter);
return View(filter);
}
你的观点将是
@model SearchModel
....
@using (Html.BeginForm("Filter", "yourControllerName", FormMethod.Get))
{
@Html.LabelFor(m => m.PriceFrom)
@Html.EditorFor(m => m.PriceFrom)
@Html.ValidationMessageFor(m => m.PriceFrom)
... // other form controls for properties you want to filter the results on
<input type="submit" value="Filter" />
}
@Html.Partial("_ResultsPartialView", Model.Products)
关于ajax - 过滤时,如何发布 SearchModel,但在 View 中获取不同的 ResultsModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48125211/