Khalid Hussain
Khalid Hussain

Reputation: 1694

How to combine a list model to another model in ASP.NET MVC3

I have two models:

public class Model1
    {
        public int? Id { get; set; }    
        public string Name{ get; set; }
        private IList<Model2> _model2; 
    } 

  public class Model2
        {
           public string Name2{ get; set; }
        }

JSON data for ajax call:

[
  {
    "Id": 1,
    "Name": "Foo",
    "Name2": "Foo2"
  },
  {
    "Id": 2,
    "Name": "Foo3",
    "Name2": "Foo4"
  }
]

Controller action:

public ActionResult Save(List<Model1> models)
        {
        }

In this way I do not get Name2 in controller action. Are there any way to get Name2 in controller?

I know it can be solved by creating another model. e.g

public class Model3
        {
            public int? Id { get; set; }    
            public string Name{ get; set; }
            private Model2 _model2; 
        } 

But I don't want to create new model class. thanks....

Upvotes: 0

Views: 1011

Answers (2)

Kosala W
Kosala W

Reputation: 2143

You can derive Model1 from Model2 like this;

public class Model1:Model2
{
    public int? Id { get; set; }    
    public string Name{ get; set; }        
} 

Now you should see Name2 as a property in Model1 and your Json should work as it is.

Upvotes: 1

Rakin
Rakin

Reputation: 1279

JSON data should be in this format

[
  {
    "Id": 1,
    "Name": "Foo",
    "_model2":[{"Name2": "Foo2"}]
  },
  {
    "Id": 2,
    "Name": "Foo3",
     "_model2":[{"Name2": "Foo4"}]
  }
]

Upvotes: 1

Related Questions