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

前端 未结 2 1357
野的像风
野的像风 2021-02-04 11:30

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 o

相关标签:
2条回答
  • 2021-02-04 12:03

    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.

    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:

    {"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

    0 讨论(0)
  • 2021-02-04 12:03

    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.

    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');
        }
    });
    
    0 讨论(0)
提交回复
热议问题