I cannot get Asp.Net MVC to bind a list of strings sent as an json object unless I wrap them in a class. I have a hard time believing that it is a must to wrap the list like that. Been looking at various examples and what not for a few hours, but cannot get any other solution to work. What am I missing? Working and non-working code below.
$.ajax({
type: "POST",
traditional: true,
url: "keyapi/activate.json",
data: JSON.stringify({ "keys": [ "1", "2" ] }),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
});
When using an action controller such as the one below "keys" will be null.
[HttpPost]
public Response<List<string>> ActivateKeys(List<string> keys)
{
return KeyService.ActivateKeys(test.Keys);
}
If I add a class to wrap the list it works. Am I forced to do so, or am I missing something here? The code below works, using the same jquery post code.
[HttpPost]
public Response<List<string>> ActivateKeys(Test test)
{
return KeyService.ActivateKeys(test.Keys);
}
public class Test
{
List<string> Keys { get; set; }
}
1 Answer 1
I'd suggest two things
1) Replace
data: JSON.stringify({ "keys": [ "1", "2" ] }),
by
data: JSON.stringify([ "1", "2" ] ), // <-- Send the array directly
doing this you'll be passing an array as parameter instead of an object containing an array propery named keys
2) If previous suggestion alone doesn't work, replace
ActivateKeys(List<string> keys)
by
ActivateKeys(IList<string> keys) // <-- Use interface IList<T>
as not 100% sure if mvc engine would be able to resolve to List<string>
2 Comments
keys
, it will assume this is parameter property and not the name of the parameter.