使用表单序列化的JSON对象post不映射到c#对象

我正在使用带有JSON对象的ajaxpost作为强类型视图中的数据。 表单序列化工作正常但在获取模型的控制器中,属性未被映射。 在Firebug中我获得了以下快照 Firebug帖子说

如何将序列化的JSON对象映射到c#对象

您将不得不复制jquery扩展以将表单转换为json对象

 (function() { $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name]) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }; })(jQuery) 

并包含json2.js库以添加对旧版浏览器的JSON.stringify()支持

然后改变你的ajax

 $.ajax({ url : '', type: 'POST', contentType : 'application/json', data : JSON.stringify($('form').serializeObject()), .... }) 

在你的情况下

 $('#frm').submit(function() { postJSON('@Url.Action("Create", "District")', JSON.stringify($('form').serializeObject()), function(result) { alert(result.Message); if (result.Success) { window.location = '@Url.Action("Index", "District")'; } }); return false; }); 

这只是一个标准的序列化forms。 它不是JSON。

你可能想看看这个 。

如果你想同时包含复选框和单选按钮,可以使用@Arun_P_Johny回答,只需要用serializeArray覆盖:

 $.fn.serializeArray = function (options) { var o = $.extend({ checkboxesAsBools: false }, options || {}); var rselectTextarea = /select|textarea/i; var rinput = /text|hidden|password|search/i; return this.map(function () { return this.elements ? $.makeArray(this.elements) : this; }) .filter(function () { return this.name && !this.disabled && (this.checked || (o.checkboxesAsBools && this.type === 'checkbox') || rselectTextarea.test(this.nodeName) || rinput.test(this.type)); }) .map(function (i, elem) { var val = $(this).val(); return val == null ? null : $.isArray(val) ? $.map(val, function (val, i) { return { name: elem.name, value: val }; }) : { name: elem.name, value: (o.checkboxesAsBools && this.type === 'checkbox') ? (this.checked ? 'true' : 'false') : val }; }).get(); }; 

应该修改serializeObject

 $.fn.serializeObject = function () { var o = {}; var a = this.serializeArray({ checkboxesAsBools: true }); $.each(a, function () { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; };