使用表单序列化的JSON对象发布未映射到C#对象 [英] JSON object post using form serialize not mapping to c# object

查看:111
本文介绍了使用表单序列化的JSON对象发布未映射到C#对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有JSON对象的ajax发布作为强类型视图中的数据.表单序列化工作正常,但是在获取模型的控制器中,属性未映射.在Firebug中,我正在获取以下快照

I'm using ajax post with JSON object as data in a strongly typed view. Form Serialization works fine but in controller while obtaining the model, the properties are not being mapped. In Firebug I'm obtaining following snap

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

How can i map the serialized JSON object to c# object

推荐答案

您将不得不将jquery扩展名复制到

You will have to copy the jquery extension to convert a form to json object

(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 库以添加支持旧版浏览器     

and include json2.js library to add JSON.stringify() support for legacy browsers       

然后将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;
});

这篇关于使用表单序列化的JSON对象发布未映射到C#对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆