【问题标题】:Why sending JSON data via POST (ajax) returns null parameter?为什么通过 POST (ajax) 发送 JSON 数据返回 null 参数?
【发布时间】:2021-02-17 02:59:41
【问题描述】:

大家下午好:)

我正在开发 asp.net mvc 应用程序。 我正在使用 JQuery DataTable 来显示我的数据。 实际上,我的 ajax Post 请求调用了一个控制器方法,该方法必须接收一些参数。 问题是它们是空的。我也有 Post 500 错误:(

这是我的课:

public class ClientSelectionFiltersViewModel
    {
        public bool StrictFilteringContractTypes { get; set; }
        public string ContractTypes { get; set; }
        public string PaymentChoices { get; set; }
        public string PopulationTypes { get; set; }
    }

这是cshtml视图的一部分:

@model ClientSelectionViewModel

@{
    ViewBag.Title = "Sélection des clients";
}

<link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" />

<h3><i class="fas fa-clipboard-list mr-3"></i> Sélection des clients</h3>
<div asp-validation-summary="All" class="text-danger mt-2"></div>

<div id="filters">
    <form method="post" asp-action="facturationWithFilters">
     <!--some code here-->...
    </form>
    <button id="btn-filter-clients" class="btn atmb-btn-blue"><i class="fas fa-filter fa-fw mr-2"></i>Filtrer les clients</button>

</div>


    <div id="client-selection" class="mt-2">

        <div class="mb-1">
            <a id="btn-send-selection" class="btn float-right atmb-btn-red">
                <i class="fas fa-feather-alt fa-fw mr-2"></i>Lancer la facturation pour les utilisateurs sélectionnés
            </a>
        </div>

        <table class="table table-striped table-hover table-sm table-bordered"
               id="tableServerSide"
               style="width:100%;">
            <thead class="thead-dark text-white">
                <tr>
                    <th>Cocher</th>
                    <th>#</th>
                    <th>Numéro de client</th>
                    <th>Types de contrats</th>
                    <th>Moyen de paiement</th>
                    <th>Population</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>



@section Scripts {

    <!--scripts DataTable-->
    <script src="~/js/modal.js"></script>
    <script src="~/lib/datatables/js/jquery.dataTables.min.js"></script>
    <script src="~/lib/datatables/js/dataTables.bootstrap4.min.js"></script>

    <!--script pour la gestion de DataTable-->
    <script type="text/javascript">

        $('#btn-filter-clients').click(function () {

            console.log($("#contractFilter").val());    //ok I get my values
            console.log($("#paymentFilter").val());     //ok I get my values
            console.log($("#populationFilter").val());  //ok I get my values
          
                console.log("début Data Table");
                $("#tableServerSide").DataTable({
                    "processing": true,
                    "serverSide": true,  
                    "filter": true,
                    "ajax": {
                        "url": "/clientselection/ajaxpostcall",
                        "type": "POST",
                        "datatype": "json",
                        "data": JSON.stringify({
                            filters: {
                                "ContractTypes": $("#contractFilter").val(),
                                "PaymentChoices": $("#paymentFilter").val(),
                                "PopulationTypes": $("#populationFilter").val(),
                                "StrictFilteringContractTypes": $("#StrictFilteringContractTypes").is(":checked")
                            }
                        }),
                        "contentType": "application/json",
                        "success": function (response) {
                            if (response != null) {
                                alert("Name : " + response.Name + ", Designation : " + response.Designation + ", Location :" + response.Location);
                            } else {
                                alert("Something went wrong");
                            }
                        },
                        "failure": function (response) {
                            alert(response.responseText);
                        },
                        "error": function (response) {
                            alert(response.responseText);
                        }
                    },
                    "columns": [ // on définit les colonnes du tableau
                        {
                            //Cases cocher
                            "data": null,
                            "className": "col-checkbox",
                            "render": function (data, type, row) {
                                var checkId = 'check' + row.id;
                                var isChecked = selectedIds.includes(checkId) ? ' checked="checked"' : '';
                                var checkbox = '<input id="' + checkId + '" type="checkbox" '
                                    + isChecked
                                    + ' class="server-checkbox" /> ';
                                /*
                                 <td class="col-checkbox sorting_1">
                                        <input id="check0" type="checkbox" class="server-checkbox">
                                 </td>
                                 */
                                return checkbox;
                            }
                        },
                        {
                            //Numéro de client
                            "data": "id",
                            "className": "col-id"
                        },
                        {
                            //Types de contrats
                            "data": "contractstypes",
                            "className": "col-contractstypes",
                            "render": function (data, type, row) {
                                var chaine = string.Join(", ", row.value);
                                return chaine;
                            }
                        },
                        {
                            //Moyen de paiement PaymentChoice
                            "data": "paymentchoice",
                            "className": "col-paymentchoice"
                        },
                        {
                            //Population PopulationType
                            "data": "populationtype",
                            "className": "col-populationtype"
                        }
                    ]
                });
            
        });

    </script>
}

这是我的控制器方法:

 [HttpPost]
        public async Task<JsonResult> AjaxPostCall(ClientSelectionFiltersViewModel filters)
        {
            //some code here....
            return Json(result);
        }

我至少有 6 个对我不起作用的解决方案,例如:

  1. 在 ajax 中:

    "数据": JSON.stringify({ 过滤器:{ 合同类型:$("#contractFilter").val(), PaymentChoices: $("#paymentFilter").val(), 人口类型:$("#populationFilter").val(), StrictFilteringContractTypes: $("#StrictFilteringContractTypes").is(":checked") } }),

然后在控制器中:

[HttpPost]
            public async Task<JsonResult> AjaxPostCall([FromBody] ClientSelectionFiltersViewModel filters)
            {
                //some code here....
                return Json(result);
            }
  1. 不要指定"contentType": "application/json",
  2. 对我的 json 数据使用不同的语法,带或不带“” ...

你能告诉我如何解决它吗? 非常感谢。

【问题讨论】:

    标签: ajax post asp.net-ajax


    【解决方案1】:
    1. 移除“contentType”
    2. 设置“数据”:jsonObject;没有 JSON.Stringy();
    3. 从控制器操作方法中删除 [FromBody]

    【讨论】:

      【解决方案2】:

      这个解决方案对我有用:

      [HttpPost]
              public async Task<JsonResult> AjaxPostCall(ClientSelectionFiltersViewModel filters, DataTableRequestParameters parameters)
              {
      //somecode...
      }
      

      在 JQuery 中:

      var filters = {
                      ContractTypes: $("#contractFilter").val().join(', '),
                      PaymentChoices: $("#paymentFilter").val().join(', '),
                      PopulationTypes: $("#populationFilter").val().join(', '),
                      StrictFilteringContractTypes: $("#StrictFilteringContractTypes").is(":checked")
                  }
      
                      $("#tableServerSide").DataTable({
                          "processing": true,
                          "serverSide": true,  
                          "filter": true,
                          "ajax": { 
                              //"url": "/clientselection/ajaxpostcall", //doesn't work!!!
                              "url": "@Url.Action("AjaxPostCall", "ClientSelection")", //ok because of tag helper
                              "type": "POST",
                              "data": filters,
      ......
      

      感谢您的帮助!!

      【讨论】:

        【解决方案3】:

        您的操作可能不需要 [FromBody];尝试将您的 JSON.stringify 更改为:

        "data": JSON.stringify({
           "ContractTypes": $("#contractFilter").val(),
           "PaymentChoices": $("#paymentFilter").val(),
           "PopulationTypes": $("#populationFilter").val(),
           "StrictFilteringContractTypes": $("#StrictFilteringContractTypes").is(":checked")
        }),
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-30
          • 2012-10-22
          • 2012-02-17
          • 2018-03-08
          • 1970-01-01
          相关资源
          最近更新 更多