background image

Simple jQuery + MVC Plugin

So I needed to create markup via javascript and json which could be easily picked up by MVC’s default model binder. This plugin takes in json and changes its structure so non-array nodes are changed to have value, id, and name members. I ended up not using json but I could see that I may use it in the future.

(function ($) {
    $.mvcname = function (json) {
        function recurseJson(json, parentID, parentName) {
            for (var key in json) {
                var item = json[key];
                var id = key, name = key;
                if(parentID){
                    id = parentID + "__" + id;
                }
                if(parentName) {
                    name = parentName + "." + name;
                }

                if($.isArray(item)) {
                for(var i = 0; i < item.length; i++) {
                    item[i] = recurseJson(item[i], id + "_" + i, name + "[" + i + "]");
                }
            } else {
                json[key] = {
                value: recurseJson(item, id, name),
                id: id,
                name: name
                };
            }
        }
        return json;
    }
    return recurseJson(json);
    };
}(jQuery));

So if you pass in some json that looks like:

var json = {
    foo: {
        a: "text",
        b: 1
    },
    bar: [
        {
            c: [2,3,4],
            d: "abc"
        },
        {
            c: [5,7,9]
            d: "text",
        }
    ]
};
$.mvcname(json);

You will end up with something like:

json = {
    foo: {
        value: {
            a: "text",
            b: 1
        },
        name: "foo",
        id: "foo"
    },
    bar: [
        {
            c: {
                value: [2,3,4],
                name: "bar[0].c",
                id: "bar_0__c"
            },
            d: {
                value: "abc",
                name: "bar[0].d",
                id: "bar_0__d"
            }
        },
        {
            c: {
                value: [5,7,9,11],
                name: "bar[1].c",
                id: "bar_1__c"
            },
            d: {
                value: "def",
                name: "bar[1].d",
                id: "bar_1__d"
            }
        }
    ]
};

Quite possibly a useless plugin but have fun…



Leave a Reply

Your email address will not be published. Required fields are marked *

Comment

You may use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>