How to handle multiple derived models with only one controller

I use ASP.NET MVC, and I have several model classes, all from the parent. I want to process all these models in one controller action, as they are almost identical, with the exception of some data fields. I want to save them in a database. How can I achieve this 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);
        }
    }
+4
source share
1 answer

you should create a ViewModel class, for example:

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 a view model object:

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 transfer this model.

0
source

All Articles