4

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);
        }
    }
Scott Simontis
  • 748
  • 1
  • 10
  • 24
DalekSupreme
  • 1,493
  • 3
  • 19
  • 32
  • 2
    this may or may not help http://stackoverflow.com/questions/9417888/mvc-3-model-binding-a-sub-type-abstract-class-or-interface – DLeh Apr 14 '15 at 17:49
  • This helped me a lot. It was more like a starting point but using reflection I managed to handle those models. – DalekSupreme Apr 16 '15 at 05:11
  • 1
    You could also create an interface and have parent model inherit from it and set your add action to a generic that inherits from that interface – Steven Ackley Apr 22 '15 at 13:48
  • Can you flatten the children and parent into one ViewModel containing both and use that instead? The minor differences between the child objects might even qualify as business logic that you could pack into the viewmodel to keep your controller nice and clean and not have to use a custom model binder or other hackery. – Brad C Apr 24 '15 at 03:00

1 Answers1

1

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.

Mostafa Azarirad
  • 629
  • 1
  • 6
  • 27