我正在尝试向ASP.NET应用程序中的iActionResult方法发出AJAX请求。该请求正在到达该方法,但在我的方法中传递给它时,其值为null。在控制台中检查selectedKommun的值时,它始终是一个数字。
$(document).ready(function () {
$('#kommun').change(function () {
var selectedKommun = $("#kommun").val();
var fordonSelect = $('#fordon');
fordonSelect.empty();
if (selectedKommun != null && selectedKommun != '') {
$.ajax({
type: "POST",
url: "/avboka?handler=GetFordon",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { "Id": selectedKommun },
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
console.log(data);
})
}
});
});
这是我发送请求的方法。我推荐了一些代码来检查Id的值。
[HttpPost]
public IActionResult OnPostGetFordon(int Id)
{
//if (!string.IsNullOrWhiteSpace(kommunFordonId) && kommunFordonId.Length == 3)
//{
// IEnumerable<SelectListItem> regions = _fordonRepo.GetFordon(kommunFordonId);
// var json = JsonConvert.SerializeObject(regions);
// return this.Content(json);
//}
//return null;
return new JsonResult(Id);
}
答案 0 :(得分:1)
代替
contentType: "application/json; charset=utf-8",
尝试
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
这是因为您没有发送JSON内容,而只是发送一个int。
由于您只发送一个int,因此您实际上也不需要指定数据类型。