Monday, May 14, 2012

Posting a JSON object graph to MVC


Passing an entire json object graph via jQuery to an MVC action method.

This covers string arrays, int arrays, dates, etc. MVC is actually pretty good at this. You just can't use jQuery's post method, as it sends the JSON object as a form post.


<script language="javascript" type="text/javascript">
    var testModel = {
                    NumberList: [100, 200, 300, 400 ],
                    NumberArray: [101, 102, 103],
                    StringArray: ["a""b""c""d"],
                    Date: new Date(),
                    Boolean: true
                };
    $(function () {
        $("#submit").click(function () {
            var model = {
                Id: 123,
                Name: "foo",
                ProductIds: [1, 2, 3, 4, 5],
                StoreIds: [11, 12, 13, 14],
                TestModel: testModel
            };
 
            $.ajax({
                url: "/Test/SaveInvoice",
                data: JSON.stringify(model),
                success: function (data, xhr) {
                    alert(data);
                },
                dataType: "json",
                contentType: "application/json",
                type: "post"
            });
        });
    });
</script>

No comments:

Post a Comment