ChiMo ChiMo - 5 months ago 7
Ajax Question

Pass custom model *with List<CustClass>* through ajax call

I am having a bit of trouble passing my json string to the jsonResult within my controller. All the first-level variables come in fine except for the

List<CustClass>
which always returns a default empty list when it should be filled with the list of objects (List<>) I passed in.

The ajax call that looks along the lines of:

var model = {
Id: id,
Name: name,
Items: [{
Name: itemName[0],
Color: itemColor[0]
},{
Name: itemName[1],
Color: itemColor[2]
}]
};

$.ajax({
url: "/@path",
type: "POST",
data: JSON.stringify(model),
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
traditional: true
});


With my C# model looking along the lines of

public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }

public class Item {
public string Name { get; set; }
public string Color { get; set; }
}
public List<Item> Items = new List<Item>();
}


And the result:

[HttpPost]
public JsonResult MyResult(MyModel model)
{
// Do Stuff
}


What am I doing wrong here? Is this even possible to do?

Answer

Dont instantiate your list to map it properly. Since binding of model takes place after instantiation of the class.

public class MyModel
{
    public int Id { get; set; }
    public string Name { get; set; }

    public class Item {
        public string Name { get; set; }
        public string Color { get; set; }
    }
    public List<Item> Items {get; set;}
}
Comments