我直接进入正题。
我正在尝试将值从我的ajax传递到 Controller 并console.log该值。但是,当我尝试 console.log 该值时,它给出错误 500..
这是我的代码:
我已经在 php 上做 ajax 很长时间了..但是,我对 asp.net C# mvc 仍然很陌生,所以请耐心等待。
AJAX:
$("#Property_ProvinceID").on("change", function () {
var $this = $(this);
var province_id = $this.val();
var $url = "/Property/GetCities";
alert("get:" + province_id);
$.ajax({
url: $url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data:{id: province_id},
success: function (data) {
console.log(data);
}
});
});
Controller :
[HttpPost]
public ActionResult GetCities(int id)
{
return Json(new { success = true });
}
这是错误,但我不知道我的 Controller 出了什么问题。
POST
http://localhost:43969/Property/GetCities
500 (Internal Server Error)
最佳答案
如果使用contentType: 'application/json; charset=utf-8'
然后使用 JSON.stringify
将发送的数据转换为 JSON 字符串。
$("#Property_ProvinceID").on("change", function () {
var $this = $(this);
var province_id = $this.val();
var $url = "/Property/GetCities";
alert("get:" + province_id);
var data = JSON.stringify({id: province_id});
$.ajax({
url: $url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: data,
success: function (data) {
console.log(data);
}
});
});
正如@StephenMuecke 的评论中提到的
It does not need to be stringified if
contentType: 'application/json; charset=utf-8'
, is removed (so that it uses the defaultapplication/x-www-form-urlencoded; charset=UTF-8'
).
关于c# - ASP.NET C# Ajax 调用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41581916/