通过 jQuery ajax 将 JSON 对象数组发布到 MVC3 操作方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6031206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:16:33  来源:igfitidea点击:

Posting array of JSON objects to MVC3 action method via jQuery ajax

jqueryajaxjsonasp.net-mvc-3

提问by jcvandan

Does the model binder not suport arrays of JSON objects? The code below works when sending a single JSON domain object as part of the ajax post. However, when sending an array of JSON domain objects, the action parameter is null.

模型绑定器不支持 JSON 对象数组吗?下面的代码在将单个 JSON 域对象作为 ajax 帖子的一部分发送时有效。但是,在发送 JSON 域对象数组时,action 参数为 null。

     var domains = [{
                        DomainName: 'testt1',
                        Price: '19.99',
                        Available: true
                    }, {
                        DomainName: 'testt2',
                        Price: '15.99',
                        Available: false
                    }];

                $.ajax({
                    type: 'POST',
                    url: Url.BasketAddDomain,
                    dataType: "json",
                    data: domains,
                    success: function (basketHtml) {

                    },
                    error: function (a, b, c) {
                        alert('A problem ocurred');
                    }
            });

This is the action method:

这是操作方法:

public ActionResult AddDomain(IEnumerable<DomainBasketItemModel> domain)
{
    ...

Any ideas if it is possible to do this?

如果有可能做到这一点,有什么想法吗?

EDIT

编辑

@Milimetric

@Milimetric

Your solution works! However, this is my fault, but the code I demonstrated isn't the real code of my problem, I was trying to show equivalent code that is easier to understand.

您的解决方案有效!然而,这是我的错,但我演示的代码并不是我问题的真正代码,我试图展示更容易理解的等效代码。

I am actually creating an array, then interating some DOM elements and pushing a JSON object onto the array, then posting this array as the data...

我实际上是在创建一个数组,然后交互一些 DOM 元素并将一个 JSON 对象推送到数组上,然后将此数组作为数据发布...

var domains = [];

                $(this).parents('table').find('input:checked').each(function () {
                    var domain = {
                        DomainName: $(this).parent().parent().find('.name').html(),
                        Price: $(this).parent().parent().find('.price span').html(),
                        Available: $(this).parent().parent().find('.available').html() == "Available"
                    }

                    domains.push(domain);
                });

                $.ajax({
                    type: 'POST',
                    url: Url.BasketAddDomain,
                    dataType: "json",
                    data: { domain: domains },
                    success: function (basketHtml) {

                    },
                    error: function (a, b, c) {
                        alert('A problem ocurred');
                    }
                });

回答by Milimetric

You need:

你需要:

var domains = { domains: [... your elements ...]};

            $.ajax({
                type: 'post',
                url: 'Your-URI',
                data: JSON.stringify(domains),
                contentType: "application/json; charset=utf-8",
                traditional: true,
                success: function (data) {
                    ...
                }
            });

In general, check out the Request object in the debugger, you'll see what's being passed and get an idea of how to "speak" HTTP.

通常,查看调试器中的 Request 对象,您将看到传递的内容并了解如何“说出”HTTP。

NOTE: Just found this out. The model binder chokes on nullable decimal properties like:

注意:刚刚发现了这一点。模型绑定器会阻塞可空的十进制属性,例如:

public decimal? latitude { get; set; }

So it won't bind that if you're posting to it with a json string that looks like this:

因此,如果您使用如下所示的 json 字符串向其发布内容,则不会绑定它:

{"latitude":12.0}

But it WILL work if you post something like this:

但是,如果您发布这样的内容,它将起作用:

{"latitude":"12.0"}

See: http://syper-blogger.blogspot.com/2011/07/hello-world.html

见:http: //syper-blogger.blogspot.com/2011/07/hello-world.html

回答by Steve Mallory

I had a similar problem. To solve it, I took a slightly different approach. Instead of a JSON object, I used arrays of hidden form variables. As long as the variable names matched up, model binding worked like a charm.

我有一个类似的问题。为了解决这个问题,我采取了一种稍微不同的方法。我没有使用 JSON 对象,而是使用了隐藏表单变量的数组。只要变量名称匹配,模型绑定就会像魅力一样工作。

function AddDomainBasket(domainName, price, available) {

    if ( typeof AddDomainBasket.counter == 'undefined' ) {
        AddDomainBasket.counter = 0;
    }

    $("#some_form").append('<input type="hidden" name="[' + AddDomainBasket.counter + '].DomainName" value="' + domainName_index + '" />');
    $("#some_form").append('<input type="hidden" name="[' + AddDomainBasket.counter + '].Price" value="' + price + '" />');
    $("#some_form").append('<input type="hidden" name="[' + AddDomainBasket.counter + '].Available" value="' + available + '" />');

    ++AddDomainBasket.counter;
}

And then submit the serlialized form

然后提交序列化的表单

$(this).parents('table').find('input:checked').each(function () {
    AddDomainBasket($(this).parent().parent().find('.name').html(),
                    $(this).parent().parent().find('.price span').html(),
                    $(this).parent().parent().find('.available').html() ==   "Available");
                }
            });

$.ajax({
    type: 'POST',
    url: Url.BasketAddDomain,
    data: $('#some_form').serialize(),
    success: function (basketHtml) {
        },
        error: function (a, b, c) {
            alert('A problem ocurred');
    }
});