开发者

Binding a JSON Array of strings to ASP.NET MVC3

Is it possible to post an array of JSON strings to MVC3 without a custom binder? The array is being created from checkbox values and I'm posting it via jQuery as follows:

var checkedItems = $(":checked").map(function () {
        return this.value;
    }).get();

    $.post("/test/delete", { Items: checkedItems });

The raw post query strings looks like this:

Items%5B%5D=test1.com&Items%5B%5D=test2.com&Items%5B%5D=test3.com

I had a look at the MVc3 source and it appears that I need to开发者_高级运维 use index values like [0], [1]. If MVC3 can't natively bind the array is there a simple way to change the post values so they have the index values required by MVC3?


You need to specify the content type to asp.net mvc so that is reads it as json, use jquery ajax function like this:

    $.ajax({
        url: "/test/delete",
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify({Items: checkedItems}),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {

        }
    });

and get json2.js to make json.stringify available on browser that do not supoprt it


You need to encode the array

{ Items: JSON.stringify(checkedItems) }

And then decode it on the other side. But be careful - JSON.stringify isn't available in IE7.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜