我的项目中有这个类:
我在 Controller 中创建了一个 JsonResult 方法,该方法具有此类中的一个对象作为参数:
[HttpPost]
public JsonResult NewAreaCode(AreaCode model)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
我试图在 Ajax 请求中调用此方法,我尝试了两种方式:
var areaCode = $(dataContent).parent().parent().find("#City_idCity").attr("value");
var City_idCity = $(dataContent).parent().parent().find("#areaCode").attr("value");
var model = JSON.stringify({ "idAreaCode": "0", "areaCode": areaCode, "City_idCity": City_idCity });
$.ajax({
type: 'POST',
url: '/Address/NewAreaCode',
data: model,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
}
});
function submitNewAreaCode(dataContent) {
var areaCode = $(dataContent).parent().parent().find("#City_idCity").attr("value");
var City_idCity = $(dataContent).parent().parent().find("#areaCode").attr("value");
var model = { "idAreaCode": "0", "areaCode": areaCode, "City_idCity": City_idCity };
$.ajax({
type: 'POST',
url: '/Address/NewAreaCode',
data: model,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
}
});
}
但我无法调用 JSON 方法。
在第一种情况下,使用 JSON.stringify 时,出现无法将 Int32 转换为 String 的错误。 在第二种情况下,直接传递对象,我收到错误“无效的 JSON 原语:idAreaCode”(或传递的任何第一个参数,没关系)。
我不明白发生了什么,因为我在另一个案例中做了类似的事情,但使用了不同的类:
我创建了一个类似的情况,将AreaCode参数更改为Country,我用下面的代码调用Ajax请求:
function editCountrySubmit(element) {
element = $(element).parent();
var divCountry = "#" + $(element).attr("id");
var div = $(divCountry).html();
var idCountry = divCountry.substring(divCountry.indexOf("-") + 1, divCountry.length);
var country = $(divCountry + " #countryName").attr("value");
var countryCode = $(divCountry + " #countryCode").attr("value");
$.ajax({
type: "POST",
url: "/Address/EditCountry",
data: { "idCountry": idCountry, "country": country, "countryCode": countryCode },
success: function (data) {
updateCountryList(data, element);
}
});}
这样,代码就可以工作了。
我是不是忘记了什么?还是我的课有问题?请记住,没有任何一个属性接受 NULL 值。
最佳答案
看起来这是因为您试图将零(“0”)的字符串
表示形式放入名为idAreaCode
的模型属性中,该属性恰好是类型int
:
var model = JSON.stringify({ "idAreaCode": "0", "areaCode": areaCode, "City_idCity": City_idCity });
试试这个:
var model = JSON.stringify({ "idAreaCode": 0, "areaCode": areaCode, "City_idCity": City_idCity });
关于c# - 在传递 JSON 对象或 JSON.stringify 时,将 JSON 传递给 JsonResult 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24955862/