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

Null parameter in Json controller method while Jquery parameter has value

我正在根据我找到的示例创建级联下拉列表 here

发送到服务器以请求第二个下拉列表值的查询具有非空参数,但是当我中断控制器方法时,它显示为空。如下所示。

如有任何帮助,我们将不胜感激!谢谢!!

它使用 jQuery 和 ASP.NET MVC 5 而我的项目是 ASP.NET MVC Core 2

控制器中的代码如下:

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);
         }
    });
}); 

既然你已经指定了contentType = "application/json"并且发送的是字符串化数据,那么你需要在POST方法中添加[FromBody]属性来指示ModelBinder使用 content-type header 确定 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