Json控制器方法中的Null参数,而Jquery参数具有值

时间:2018-09-18 11:06:15

标签: c# jquery asp.net-core-mvc html-helper asp.net-core-mvc-2.0

我正在根据发现的here

示例创建级联下拉列表。

发送到服务器以请求第二个dropdownlist值的查询具有非null参数,但是当我在controller方法中中断时,它显示为空。正如您在下面看到的。

任何帮助将不胜感激!谢谢!!

parameter Country is null query from Chrome inspector

当我的项目是ASP.NET MVC Core 2时,它正在使用jQuery和ASP.NET MVC 5

控制器中的代码如下:

public JsonResult States(string Country)
{
  List<string> StatesList = new List<string>();
  switch (Country)
  {
     case "India":
       StatesList.Add("New Delhi");
       StatesList.Add("Mumbai");
       StatesList.Add("Kolkata");
       StatesList.Add("Chennai");
       break;
  }
  return Json(StatesList);
}

这是AJAX:

<script src = "/lib/jquery/dist/jquery.js" > </script>
<script> 
$(document).ready(function ()
{
    $("#State").prop("disabled", true);
    $("#Country").change(function ()
    {
        if ($("#Country").val() != "Select")
        {
             var CountryOptions = {};
             CountryOptions.url = "/Dropdown/states";
             CountryOptions.type = "POST";
             CountryOptions.data = JSON.stringify({ Country: $("#Country").val() });
             CountryOptions.datatype = "json";
             CountryOptions.contentType = "application/json";
             CountryOptions.success = function (StatesList)
             {
                $("#State").empty();
                for (var i = 0; i < StatesList.length; i++)
                {
                     $("#State").append("<option>" + StatesList[i] + "</option>");
                }
                $("#State").prop("disabled", false);
             };

            CountryOptions.error = function ()
            {
                alert("Error in Getting States!!");
            };
            $.ajax(CountryOptions);
        }
        else
        {
             $("#State").empty();
             $("#State").prop("disabled", true);
         }
    });
}); 

1 个答案:

答案 0 :(得分:1)

由于您已指定contentType = "application/json"并正在发送字符串化数据,因此您需要在POST方法中添加[FromBody]属性,以指示ModelBinder使用content-type标头确定用于读取请求的IInputFormatter(对于json,JsonInputFormatter)。将方法的签名更改为

[HttpPost]
public JsonResult States([FromBody]string Country)

但是,没有必要将数据作为json发送,您可以使用默认的contentType'application/x-www-form-urlencoded; charset=UTF-8')。您可以删除contentType选项并使用

CountryOptions.data = { Country: $("#Country").val() }; // not stringified
// CountryOptions.contentType = "application/json";

有关更多信息,请参见Model binding JSON POSTs in ASP.NET Core