user3348273
user3348273

Reputation: 33

MVC method not receiving json array as List

My MVC method is receiving the rest of my model, but not my list

javascript:

var userSettings = [ { Name: "SettingName", Value: "SettingValue" }, { Name: "SettingName1", Value: "SettingValue2" }];

var data = {
    Email: "[email protected]",
    Password: "123",
    ConfirmPassword: "123",
    UserSettings: JSON.stringify(userSettings)
}

$.ajax({
    url: this.action,
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(data)

})

C#/MVC

[HttpPost]
public ActionResult Create(CreateUser model)
{
    //stuff
}

public class CreateUser
{
    public string Email { get; set; }
    public string Password { get; set; }
    public string ConfirmPassword { get; set; }
    public List<NameValue> UserSettings { get; set; }
}

public class NameValue
{
    public string Name { get; set; }
    public string Value { get; set; }
}

What am I missing here? How come my UserSettings always comes through empty?

If I change UserSettings to String instead of List it receives the json string, but I can't get it to receive it as a list

Upvotes: 2

Views: 823

Answers (2)

Steve Andrews
Steve Andrews

Reputation: 559

You are JSON stringifying the settings twice, once in the data object, and again in the AJAX call.

Try:

UserSettings: userSettings

For working with JSON data, I find Fiddler to be an immense help in finding serialization problems.

Upvotes: 0

Rowan Freeman
Rowan Freeman

Reputation: 16348

Don't stringify userSettings.

Doing so will create strings with escaped quotes and MVC won't know how to bind it.

With stringify:

"{"Email":"[email protected]","Password":"123","ConfirmPassword":"123","UserSettings":"[{\"Name\":\"SettingName\",\"Value\":\"SettingValue\"},{\"Name\":\"SettingName1\",\"Value\":\"SettingValue2\"}]"}"

Without stringify:

"{"Email":"[email protected]","Password":"123","ConfirmPassword":"123","UserSettings":[{"Name":"SettingName","Value":"SettingValue"},{"Name":"SettingName1","Value":"SettingValue2"}]}"

Your code should look like:

var data = {
    Email: "[email protected]",
    Password: "123",
    ConfirmPassword: "123",
    UserSettings: userSettings
}

Upvotes: 2

Related Questions