ajax - 过滤时,如何发布 SearchModel,但在 View 中获取不同的 ResultsModel

标签 ajax asp.net-mvc razor filter view

我正在创建一个过滤器 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/

相关文章:

asp.net-mvc - MVC 6 中 @Scripts.Render 的替代品是什么

asp.net-mvc - Razor .NET 无法识别代码脚本

c# - Asp.net MVC Razor如何显示两个模型字段的分组单选按钮

javascript - Ajax 在 setInterval 上被调用两次

java - spring mvc ajax数据用Jackson截断

ASP.NET Razor Entity Framework 针对模型使用 Case 语句

asp.net-mvc - Razor Engine - 如何在引号内转义@?

javascript - Microsoft JScript 运行时错误 : Function expected

javascript - 在 Chrome 扩展程序中在后台执行多个 ajax 请求

c# - Razor View - @if 语句编译错误