【问题标题】:How to pass a collection of <Model> from view to Controller in .net mvc如何将 <Model> 的集合从视图传递到 .net mvc 中的控制器
【发布时间】:2019-03-19 06:22:54
【问题描述】:

感谢您花时间阅读我的问题.... 解决方案不必与 ajax 一起使用......我需要任何东西来使这项工作如所述......

我需要做以下事情 Image for the site 如果我从广告类型中选择私家车,它只会显示私家车,如果我选择BMW,则让它只显示BMW,以此类推以进行其余的搜索。 ..我做到了..

问题是当我尝试组合多个搜索参数时

示例:如果我只需要显示 BMW 和特定城市的私人二手车,并按价格或里程等对结果进行排序......

我没能做到这一点...我尝试每次将结果包装为一个列表,然后通过 ajax 将此列表传递给控制器​​以执行操作,然后在部分视图中检索它...但我无法通过此列表(列表(Class UserCar))...... 我认为如果一个慷慨的人指导我正确排序,所有搜索参数都是一样的......

这是包含用户汽车模型的视图模型,其中包含我想从数据库中检索的所有数据

public class VMUserCar
{
    public UserCar UserCar { get; set; }
    public IEnumerable<UserCar> CarsList { get; set; }
    public int? CarsListCount{ get { return CarsList.Count(); } }
}

这是包含部分视图的索引

<div class="searchDiv">
@Html.Partial("~/Views/Partial_Views/_DisplayAds/_SearchResultDisplay.cshtml")
 </div>

这是显示在上面的站点图像中显示的所有 userCars 的部分视图(我尽可能删除了 html 以尽量减少干扰)

@model CarSales.Models.CarsForSale.VMUserCar

@foreach (var item in Model.CarsList)
{
 @item.Year  @item.Make  @item.Model @item.Badge @item.BodyStyle 
 @item.DriveType   --&& Other stuff--
}

   @*SortBy (in the same view)*@
<script>
    $(document).ready(function () {
        var SortDD = $('#SortDD');
        var searchDiv = $('.searchDiv');
       
        var carsList = '@Html.Raw(Json.Encode(Model.CarsList))';
        //var carsList1 = JSON.stringify(carsList);
        console.log("List: " + carsList);

      SortDD.change(function () {
            $.ajax({
                //processData: false,
                traditional: true,
                dataType: 'html',
                contentType: 'application/json; charset=utf-8',
                data: { list: carsList,searchValue: SortDD.val() },
                url: '@Url.Action("SortSearch", "DisplayAds")',
                type: 'post',
                success: function (response) {
                    searchDiv.empty();
                    if (response !== null) {
                        searchDiv.append(response);
                    } else {
                        searchDiv.append("Search returns null from sort DD");
                    }
                },
                error: function (ex) {
                    alert("Error from sort DD:  ", ex.statusText);
                }
            });
        });
    });
     </script>

这是接收ajax的控制器

[HttpPost]
    public PartialViewResult SortSearch(string searchValue, IEnumerable<UserCar> list)
    {

        ViewBag.SortDD = new SelectList(Utilties.GetSortDD(), "Value", "Text", searchValue);

        switch (searchValue)
        {
            case "1":
                list = list.OrderByDescending(x => x.AdCreationDate).ToList();
                break;

            case "2":
          list = list.OrderByDescending(x => x.Odometer).ToList();
                break;

            case "3":
               list = list.OrderBy(x => x.Make).ToList();
                break;
          --& other 10 cases--

   var vmUserCar = new VMUserCar() { CarsList = list};

        return PartialView("~/Views/Partial_Views/_DisplayAds/_SearchResultDisplay.cshtml",  vmUserCar );
    } --this is the same partial view which displays all the userCars --

当我运行并且 ajax 包含: 内容类型:'应用程序/json;字符集=utf-8', 它给了我“无效的 JSON 原语:list1”。并且没有继续行动......

& 当我在没有它的情况下运行时,它会起作用,但控制器上的列表值始终为空.. 我单独尝试了 '@Html.Raw(Json.Encode(Model.CarsList))' 并且值始终为 null 但是当我 console.log 它时......我得到 json 值..

和 JSON.stringify(carsList) 也为空,但当我控制台记录它时根本没有值...

当我将控制器的列表值更改为 IEnumerable 列表时 它将值检索为一个长字符串行,但我不知道如何将其转换为 UserCar 类

再次感谢您花时间阅读所有内容...任何帮助将不胜感激....

【问题讨论】:

  • 怎么了?问题不清楚吗?有这么难吗??任何反馈请..

标签: json ajax asp.net-mvc arraylist web-development-server


【解决方案1】:
      $(document).ready(function () { 
       function PassThings()
       {              
           var things = [
               { id: 1, color: 'yellow' },
               { id: 2, color: 'blue' },
               { id: 3, color: 'red' }
           ];

           things = JSON.stringify({ 'things': things });

           $.ajax({
               contentType: 'application/json; charset=utf-8',
               dataType: 'json',
               type: 'POST',
               url: $("body").attr("data-project-root") + "Administration/Actions/PassThings",
               data: things,
               success: function () {
                   $('#result').html('"PassThings()" successfully called.');
               },
               failure: function (response) {
                   $('#result').html(response);
               }
           }); 
       }
       PassThings();
   });

对于这个控制器 ::

   public void PassThings(List<Thing> things)
    {
        var t = things;
    }

对于这个 ViewModel::

public class Thing
{
    public int Id { get; set; }
    public string Color { get; set; }
}

它一定是有效的,我重新检查一下。请你重新检查一下。

【讨论】:

  • 感谢重播,我试过了...之后: JSON.stringify({ 'things': things });它给了我正确的 json .....但是在控制器的值中它始终为空,如果我将类值设为 它接受 json 但它显示长字符串行...不知道如何使用那...
  • 重新检查了一遍......是的,使用时同样的错误:contentType:'application/json; charset=utf-8', 在 ajax 中它给出(无效的 JSON 原语:list.),当我删除内容类型时.. 它使用正确的数据传递 json 但只有当我将接收器设为 List 其他类型时给我空...
  • 虽然我用 json validattor jsonformatter.curiousconcept.com 检查了 json 并告诉我有效的 json ...我仍然收到错误无效 json 原语....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-02
  • 2013-05-23
  • 2019-01-02
  • 2016-12-28
  • 1970-01-01
  • 2018-12-08
相关资源
最近更新 更多