Kimpo
Kimpo

Reputation: 5836

Json modelbinder not working on nested List<T> Asp.Net MVC 3

I'm sending a JSON object to an action method. Everything works client side and the JSON object looks correct but the only values that are set are simple properties. The count on List is always 0.

Here is an example of a JSON object sent to the server. I just alerted the whole JSON string and pasted it below:

{"Tags":"
[{\"Id\":0,\"Title\":\"Windows 8\",\"TagType\":\"Generic\"},{\"Id\":0,\"Title\":\"Dreamweaver\",\"TagType\":\"Generic\"},{\"Id\":0,\"Title\":\"Word\",\"TagType\":\"Generic\"}]",
"CurrentPage":"5",
"ItemsPerPage":"10",
"SearchPhrase":"blaha"}

Here are the C# classes:

public class SearchParams
{
    public List<Tag> Tags { get; set; }
    public string ItemsPerPage { get; set; }
    public string SearchPhrase { get; set; }
    public string CurrentPage { get; set; }
}

public class Tag
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string TagType { get; set; }
}

Here is the Action method:

 public JsonResult Search(SearchParams searchParams)
 {
    //Stuff happens here
 }

Model binding is working for the three string properties:

ItemsPerPage == 10
SearchPhrase == "blaha"
CurrentPage == 5
Tag.Count == 0 ????  

There should be 3 Tag items here :(

Am I missing something obvious here?

br

Kim

Upvotes: 0

Views: 872

Answers (2)

Trober
Trober

Reputation: 269

This is old, but for the record a default constructor creating the generic list is what I do and it always works:

public class SearchParams
{
    public List<Tag> Tags { get; set; }
    public string ItemsPerPage { get; set; }
    public string SearchPhrase { get; set; }
    public string CurrentPage { get; set; }

    public SearchParams() {
        Tags = new List<Tag>();
    }
}

Upvotes: 0

FrontEnd Expert
FrontEnd Expert

Reputation: 5803

first check your json ..

{     "Tags": " [{\"Id\":0,\"Title\":\"Windows 8\",\"TagType\":\"Generic\"},{\"Id\":0,\"Title\":\"Dreamweaver\",\"TagType\":\"Generic\"},{\"Id\":0,\"Title\":\"Word\",\"TagType\":\"Generic\"}]",     "CurrentPage": "5",     "ItemsPerPage": "10",     "SearchPhrase": "blaha" }

I tested it by json validator there are some error in your json..

    http://jsonlint.com/

http://jsonformatter.curiousconcept.com/

check it..

Upvotes: 3

Related Questions