Subtype Handling in ASP.NET MVC

I can’t come up with a “better” way to handle the following situation - basically, I have a bunch of stored objects that inherit from the base type and would like to get them from the repository, find its subtype (possibly via "if (x is y)" ), and then act accordingly - some of them use a common implementation, others with dedicated logic and representations.

I think [truncated] it will look something like this:

/vehicle/details/1234

- Views
  - Vehicle
    - Details.aspx

abstract class Vehicle{
  public int ID{ get; }
}
class Motorbike : Vehicle{
  //whatever  
}
class Car : Vehicle{
  public int NoOfDoors{ get; }
}

class VehicleController : Controller{
  VehicleRepository _vehicleRepository; //injected, etc
  public ActionResult Details(int id){
    var vehicle = _vehicleRepository.Get(id);
    //we can now figure out what subtype the vehicle is
    //and can respond accordingly
  }
}

Now, if we don’t worry about future expansion and maintenance, and all of this, we can go the dark way and implement something like the following - which will function normally, but will undoubtedly be an [absolute] nightmare.

- Views
  - Vehicle
    - Details.aspx
    - CarDetails.aspx

public ActionResult Details(int id){
  var vehicle = _vehicleRepository.Get(id);
  return (vehicle is Car) ? DetailsView((Car)vehicle) : DetailsView(vehicle);
}
private ActionResult DetailsView(Car car){
  var crashTestResults = GetCrashTestResults(car);
  var carData = new CarDetailsViewData(car, crashTestResults);
  return View("CarDetails", carData);
}
private ActionResult DetailsView(Vehicle vehicle){
  var vehicleData = new VehicleDetailsViewData(car, crashTestResults);
  return View("Details", vehicleData);
}

- , , ...

- Views
  - Vehicle
    - Car
      - Details.aspx
    - Motorbike
      - Details.aspx

public ActionResult Details(int id){
  var vehicle = _vehicleRepository.Get(id);
  return View(vehicle.GetType().Name + "\Details", vehicle);
}

, , , , , , ...

, , , "VehicleController" , , .

.

+3
3

, , , :

1) GetViewName GetViewData, , .

2) GetViewData, , ViewData . ViewData , HTML if (ViewData is IHasCrashTestData) - .

1 .

0

, , , , (, - ).

, , , . , CRUD?

, , MVC 2 DisplayFor EditorFor functioniity. , (iirc, ).

, , MVC 2, RC -, RTM, - ViewEngine (, ), , , , , .

0

Why do you want to create a new controller for all types of vehicles. In the NM database, the association will be simple and flexible.

VehicleTypes
    ->Id
    ->Name

VehicleTypeVariables
    ->Id
    ->Name

Vehicles
    ->Id
    ->VehicleTypeId

VehicleVariables
    ->Id
    ->VehicleId
    ->VehicleTypeVariableId
    ->Value
-1
source

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


All Articles