2

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 Firebug post states

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

serene
  • 685
  • 6
  • 16
  • you are not submitting a json object here, json value will be like `{DistrictID: '13', RegionID: '1', ...}` – Arun P Johny Apr 02 '13 at 05:37
  • Can you share the javascript also – Arun P Johny Apr 02 '13 at 05:38
  • how do i do that then..? – serene Apr 02 '13 at 05:40
  • ` $('#frm').submit(function () { postJSON('@Url.Action("Create", "District")', $('#frm').serialize(), function (result) { alert(result.Message); if (result.Success) { window.location = '@Url.Action("Index", "District")'; } } ); return false; });` is for using post while postJSON is my customized json object posting jquery function – serene Apr 02 '13 at 05:41
  • how do i map my form serialized object to JSON object..?? – serene Apr 02 '13 at 05:42

3 Answers3

2

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)

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

Then change you ajax to

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

In your case

$('#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;
});
d.popov
  • 4,175
  • 1
  • 36
  • 47
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

That is just a standard serialized form. It is not JSON.

You may want to look at this.

Community
  • 1
  • 1
Iain
  • 2,259
  • 1
  • 16
  • 18
0

If you want to include also checkboxes and radio buttons, @Arun_P_Johny answer can be used, just serializeArray should also be overwritten with this:

$.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 should be modified

$.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;
};
d.popov
  • 4,175
  • 1
  • 36
  • 47