发帖JSON到MVC控制器 - 字符串参数为null [英] posting JSON to MVC controller - String parameter is null
问题描述
我故意尽量不使用控制器参数绑定,所以我有一个控制器,它看起来像:
I am intentionally trying NOT to use a binding in the controller parameter, so I have a controller that looks like:
[HttpPost]
public ActionResult UntypedForm(String serializedformdata)
{
//// ...
}
当我张贴的JSON序列化表单元素与低于code控制器:
When I post serialized JSON form elements to the controller with the below code:
var formelements = $('#form').serializeArray();
$.post(url, formelements, function (data) {
}, "json").error(function () {
alert("Error posting to " + url);
});
我得到的字符串serializedformdata我控制器上的NULL值。然而,当我与一个强类型的对象替换字符串serializedformdata,如预期正常结合的作品。
I get a NULL value for String serializedformdata on my controller. However, when I replace String serializedformdata with a strongly-typed object, binding works properly as expected.
我的控制器整点是通用的JSON的帖子,在这里我将创建一个文件BSON放置到一个蒙戈数据库。 SO ....我故意不想要模型绑定,我想序列化的字符串作为pamameter。为什么我的serializedformdata字符串空当我张贴?
The whole point of my controller is generic JSON posts, where I will create a BSON document to place into a Mongo database. SO....I intentionally DO NOT want model binding and I want the serialized string as pamameter. Why is my serializedformdata string null when I post?
请注意 - 我也试图绑定到词典以
Note - I also tried to bind to Dictionary with
public ActionResult UntypedForm(Dictionary<string,string> serializedformdata)
{
//// ...
}
但serializedformdata仍然是空。
but serializedformdata is still null.
推荐答案
功能 serializeArray
创建了窗体的键/值对的Javascript对象。你不希望出现这种情况,你想与 serializedformdata code> =(JSON字符串)一个键/值。也就是说,这样的;
The function serializeArray
creates a Javascript object with the form's key/value pairs. You don't want that, you want a single key/value with serializedformdata
= (JSON string). Ie, like this;
var formelements = { serializedformdata: JSON.stringify($('#form').serializeArray()) };
这传递的原始JSON字符串到控制器的参数。您可以使用的JavaScriptSerializer
来获取服务器上的对象:
This passes the raw JSON string to the controller's parameter. You can use the JavaScriptSerializer
to get the object on the server:
var obj = (List<Dictionary<string,string>>)new JavaScriptSerializer().Deserialize(serializedformdata, typeof(List<Dictionary<string,string>>));
Dictionary<string,string> dict = obj.First();
string someval = dict["somekey"];
这篇关于发帖JSON到MVC控制器 - 字符串参数为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!