kriss
kriss

Reputation: 1015

MVC Controller List in model not binding

I have an action in my MVC Controller

public FileStreamResult CustomerOrdersAsExcel(ExcelColumn column)

ExcelColumn model :

public class ExcelColumn
{
    public string Header { get; set; }

    public List<EnumLocalized> EnumLocalizations { get; set; }
}

then I use ajax to pass my ExcelColumn

let ajaxSettings = {
    type: 'GET',
    xhrFields: { responseType: 'blob' },
    data: column,
    contentType: 'application/json; charset=utf-8',
    success: (data) => {
        ... on success
        }
    }
};

Column is object that has

"{"header":"Order type",
  "enumLocalizations":[ 
   {  
      "key":1,
      "value":"Customer order"
   },
   {  
      "key":2,
      "value":"Webshop"
   },
   {  
      "key":4,
      "value":"Service order"
   }
]}"

Now when I receive data in my controller Header is bound ok, but EnumLocalizations is not. It has 3 elements where each element is filled with default value Key = 0 and Value = null. I have tried to JSON.stringfy this and using traditional: true for jquery settings but neither of that worked. Do you know what may cause that binding fail?

UPDATE: I think the error is in sent format by jquery which is

header:Order type
enumLocalizations[0][key]:1
enumLocalizations[0][value]:Customer order
enumLocalizations[1][key]:2
enumLocalizations[1][value]:Webshop
enumLocalizations[2][key]:4
enumLocalizations[2][value]:Service order

I think it should be something like

header:Order type
enumLocalizations[0].key:1
enumLocalizations[0].value:Customer order
enumLocalizations[1].key:2
enumLocalizations[1].value:Webshop
enumLocalizations[2].key:4
enumLocalizations[2].value:Service order

Do you know how can I change that?

Upvotes: 1

Views: 536

Answers (2)

GGO
GGO

Reputation: 2748

Like @Dabbas said, change the ajax method to POST for sending big data (max url length is 255 characters), and don't use JSON to bind data, it's not necessary.

Try that, if didn't work, i'll remove :

var obj = {
    "header":"Order type",
    "enumLocalizations":[ 
         {  
          "key":1,
          "value":"Customer order"
         },
         {  
          "key":2,
          "value":"Webshop"
         },
         {  
          "key":4,
          "value":"Service order"
         }
    ]
};

let ajaxSettings = {
    type: 'POST',
    xhrFields: { responseType: 'blob' },
    data: obj,
    success: (data) => {
        ... on success
        }
    }
};

Upvotes: 2

Dabbas
Dabbas

Reputation: 3230

You can't use GET to send big amount of data, use POST instead.
GET will send all data through URL (which is limited to about 2000 characters depending on the browser)

let ajaxSettings = {
    type: 'POST',
    xhrFields: { responseType: 'blob' },

    dataType: 'json',

    contentType: 'application/json; charset=utf-8',
    success: (data) => {
        ... on success
        }
    }
};

Upvotes: 2

Related Questions