【发布时间】:2018-09-18 11:06:14
【问题描述】:
我正在根据我找到的示例创建一个级联下拉列表 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);
}
});
});
【问题讨论】:
-
尝试将
[FromBody]参数添加到方法中 - public JsonResult States([[FromBody] string Country)` - 但没有理由将其发送为application/json- 您可以删除contentType选项并使用CountryOptions.data = { Country: $("#Country").val() }; -
^^ 那或者用
[HttpPost]属性标记控制器方法。 -
感谢@StephenMuecke 确实没有像
application/json那样发送它! -
@Archer,[HttpPost] 不起作用,但谢谢!
-
如果方法是
[HttpPost]并且您使用[FromBody]属性,它应该可以工作
标签: c# jquery asp.net-core-mvc html-helper asp.net-core-mvc-2.0