Binding an ASP.NET MVC 3.0 Model to Base and Derived Classes?

Hi everyone, I have a base class called Vehicle, and I have all the properties common to all vehicles, and I have several derived classes called Car, Jeep that come from Vehicle and add additional properties.

Example:

public class Vehicle { public int Color { get; set; } public double Cost { get; set; } } public class Car : Vehicle { public SelectListItem Option { get; set; } } 

I have a page class in which I have a list of vehicles such as

 public class Page { public List<Vehicle> vehicles { get; set; } } 

My view is strongly related to the page class, so, in my opinion, I look at all the vehicles to display them on the page as follows: This code is inside @using (Html.BeginForm ()), so we are sending back the user's selection

  for(int i=0;i<Model.Vehicles.Count;i++) { <div id="Question"> @{ @Html.EditorFor(m => m.Vehicle[i], VehicleConstants.GetTemplateName(Model.Questions[i])); } <br /> </div> } 

I use one editor template for each type of vehicle, so calling the VehicleConstants.GetTemplateName function returns the name of the template used depending on the type of vehicle.

This template simply records the properties of a car class or Jeep class (Derived + Base class)

The problem I am facing is when the form is submitted back. I can only access the properties of the base class. Vehicle in my controller. I cannot get a value for the properties of a subclass of a car or a jeep.

  [HttpPost] public string ReadPost(Page page) { } 

What is the best way to get these values โ€‹โ€‹automatically when the form is submitted back?

Does the custom binder class create my only option? So can anyone provide me some code examples on how to do this? Any help is greatly appreciated.

+6
source share
1 answer

To do this, you will have to use a custom mediator. By default, the binder model does not know which specific type to instantiate. You can include a hidden field inside each row by specifying the specific type that will be created by your custom mediator. I have shown this in action here . By the way, note that using the standard template naming convention, you can get rid of the for loop you are using, as well as the VehicleConstants.GetTemplateName method.

+6
source

Source: https://habr.com/ru/post/914933/


All Articles