如何将serializeArray作为json传递给MVC控制器 [英] How to pass a serializeArray as json to MVC controller
问题描述
我有一个表单,我希望将其数据传递给我的控制器.这是我正在进行的jQuery调用-
I have a form whose data I want to be passed to my controller. This is the JQuery call that I am making -
var data = $form.serializeArray();
var options = {
contentType: "application/json",
url: "/Form/Save",
data: JSON.stringify(data),
type: "post",
datatype: "html",
success: function (result, xhr, status) {
console.log(result);
},
error: function (xhr, status, error) {
// redirect to error page
}
};
$.ajax(options);
这就是我在控制器中收到此消息的方式-
And this is how I am recieving this in controller -
public ActionResult Save(string paramJson)
{
// save paramJson
return null;
}
但是我在保存"操作中收到的只是paramJson = null.我也在下面尝试-
But all I am recieving in Save action is paramJson = null. I tried below as well -
数据:JSON.stringify({paramJson:data})
data: JSON.stringify({paramJson: data})
但是没有用.在这里应该做什么?
but it didn't work. What should be done here?
推荐答案
我从上述答案中得到了一些提示,并且能够提出一个对我来说非常有效的解决方案.我现在收到formname: formvalue
而不是name: formname, value: formvalue
格式的json.这是-
I took some hint from above answer and was able to frame a solution which works perfectly for me. I am now recieving a json in the format of formname: formvalue
instead of name: formname, value: formvalue
format. Here it is -
var json = {};
// converting to formname:formvalue format
$.each($form.serializeArray(), function (i, field) {
json[field.name] = field.value || '';
});
// stringify the parameter
var data = { paramJson: JSON.stringify(json) };
var options = {
contentType: "application/json",
url: "/Form/Save",
data: JSON.stringify(data),
type: "post",
datatype: "html",
success: function (result, xhr, status) {
console.log(result);
},
error: function (xhr, status, error) {
// redirect to error page
}
};
$.ajax(options);
这篇关于如何将serializeArray作为json传递给MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!