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

5
  • you are not submitting a json object here, json value will be like {DistrictID: '13', RegionID: '1', ...} Commented Apr 2, 2013 at 5:37
  • Can you share the javascript also Commented Apr 2, 2013 at 5:38
  • how do i do that then..? Commented Apr 2, 2013 at 5: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 Commented Apr 2, 2013 at 5:41
  • how do i map my form serialized object to JSON object..?? Commented Apr 2, 2013 at 5:42

3 Answers 3

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;
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

You may want to look at this.

Comments

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;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.