ASP.Net MVC 3 - JSON Model binding to array

前端 未结 3 1766
谎友^
谎友^ 2020-12-28 17:32

I am on ASP.Net MVC 3, and going by the feature list supported in at, i should be able to get default json model binding working out of the box. However i havent been succes

相关标签:
3条回答
  • 2020-12-28 17:55

    while @thanikkal answered this particular question, I had the same symptoms and a very similar setup.

    instead of the public or { get; set; } in my models causing the model binding to not work it was actually my jQuery method! (RAWR!)

    I was using $.post (which didn't work) instead of $.ajax.


    Doesn't Work:

    $.post("/Games/Action",
       { "userId": "1", "listName": [ { "fooId": "2", "barId": "99" } ] },
       'json',
       true
      );
    

    The values are in the Form.Data[], but are not mapped properly.


    Works:

     $.ajax(
        {
            url: '/Games/Action',
            type: 'POST',
            data: JSON.stringify({ userId: "1", listName: [ { fooId: 2, barId: 99 } ] }),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (data, textStatus, jqXHR)
            {
                console.log(data);
            },
            error: function (objAJAXRequest, strError)
            {
                console.log(data);
            }
        });
    

    All values mapped correctly.


    Lost a few hours to this one, hope this helps others.

    0 讨论(0)
  • 2020-12-28 18:00

    Your code looks fine.. But check this

    1. Routing settings.
    2. Put [HttpPost] attribute on SaveDiscount

    and try this

    var catalogDiscount = JSON.stringify( { discounts: jsondatacoll } );
    

    that would give make right data binding.

    0 讨论(0)
  • 2020-12-28 18:13

    As Cresnet Fresh rightly pointed out in the comments to the question the model properties must be marked public.

    So modifying Discount class as below resolved this.

    public class Discount
    {
        public string Sku{get; set;}
        public string DiscountValue{get; set;}
        public string DiscountType{get; set;}
    
    }
    
    0 讨论(0)
提交回复
热议问题