I am using ASP.NET MVC and I have several model classes all derived from the parent object. I want to handle all of these models in one controller action since they are nearly identical with the exception of some data fields. I want to save them to a database. How can I achieve such a behavior?
Example:
class ParentModel {...}
class ChildModel1 : ParentModel {...}
class ChildModel2 : ParentModel {...}
class ChildModel3 : ParentModel {...}
class ChildModel4 : ParentModel {...}
public class ModelController : Controller
{
//But with this I want to handle all the child objects as well
//And add them automatically to the database.
public ActionResult Add(ParentModel model)
{
db.ParentModel.Add(model);
}
}
you should create a ViewModel Class such as :
public class viewmodel
{
public ChildModel1 childModel1 { get; set; }
public ChildModel2 childModel2 { get; set; }
public ChildModel3 childModel3 { get; set; }
public ChildModel4 childModel4 { get; set; }
}
then create an object of view model:
viewmodel v = new viewmodel();
now you can add your child model to the view model:
v.childModel1 = yourchildmodel1;
v.childModel2 = yourchildmodel2;
v.childModel3 = yourchildmodel3;
v.childModel4 = yourchildmodel4;
now you can pass this model.