Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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; }
}
share|improve this question

1 Answer 1

up vote 2 down vote accepted

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>

share|improve this answer
    
Your first suggestion worked wonders. No need to use the interface. So there's no need to map the array to the parameter name. Why is that? –  user1323245 Feb 20 '14 at 14:26
    
Because mvc engine will try to convert your exact json object to method parameter, if you add an extra level to define keys, it will assume this is parameter property and not the name of the parameter. –  Claudio Redi Feb 20 '14 at 14:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.