[英]Controller does not get json data
I'm trying to pass json data from view to controller but controller getting null all the time I tried every thing to resolve this issue but didn't find any solution here is my controller and json data 我正在尝试将json数据从视图传递到控制器,但是控制器在尝试解决此问题的所有过程中一直都为空,但这里找不到任何解决方案,这是我的控制器和json数据
$("#ex_save").on("click",function() {
var array = @Html.Raw(Json.Encode(Model));
var json = JSON.stringify(array);
$.ajax({
type: "POST",
url: "/Equipment/BulkUpdate",
data: { jsonCollection : json },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
console.log("Saved");
},
error: function (e) {
console.log(e);
}
});
});
this my ajax method to pass data to controller. 这是我的ajax方法,用于将数据传递给控制器。 and here is my controller to get that data :-
这是我的控制器来获取数据:-
[HttpPost]
public ActionResult BulkUpdate(string jsonCollection)
{
try
{
return View();
}
catch
{
throw;
}
}
You need to do this 你需要这样做
$("#ex_save").on("click",function() {
var array = @Html.Raw(Json.Encode(Model));
var jsonData = {jsonCollection : array};
var postJson = JSON.stringify(jsonData);
$.ajax({
type: "POST",
url: "/Equipment/BulkUpdate",
data: postJson,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
console.log("Saved");
},
error: function (e) {
console.log(e);
}
});
});
What you were doing is that you have used JSON.stringify()
to convert the JSON in array
variable and then you were assigning this to the new JSON object { jsonCollection : json }
as POST request body. 您正在执行的操作是使用
JSON.stringify()
转换array
变量中的JSON,然后将其分配给新的JSON对象{ jsonCollection : json }
作为POST请求主体。 So it is a valid json object like {'name':'test1', 'age':'12'}
then jQuery might not send it as json data but instead serialize it to name=test1&age=12
thus you get the error "Invalid JSON primitive: name"
因此它是一个有效的json对象,例如
{'name':'test1', 'age':'12'}
然后jQuery可能不会将其作为json数据发送,而是将其序列化为name=test1&age=12
因此您会收到错误消息"Invalid JSON primitive: name"
And in your case, "Invalid JSON primitive: jsonCollection"
. 在您的情况下,
"Invalid JSON primitive: jsonCollection"
。 So try using above code. 因此,请尝试使用上面的代码。
$("#ex_save").on("click",function() {
var array = @Html.Raw(Json.Encode(Model));
var jsonData = {jsonCollection : array};
var postJson = JSON.stringify(jsonData);
$.ajax({
type: "POST",
url: "/Equipment/BulkUpdate",
data: postJson,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
console.log("Saved");
},
error: function (e) {
console.log(e);
}
});
});
And instead of getting string at controller try to get ICollection 而不是在控制器上获取字符串,而是尝试获取ICollection
[HttpPost]
public ActionResult BulkUpdate(ICollection<your_class_type> jsonCollection)
{
try
{
return View();
}
catch
{
throw;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.