Hi, I can't think of a "best" way of handling the following situation - basically, I have a bunch of stored objects that inherit from a base type and would like to be able to retrieve one from storage, find its subtype (perhaps via "if(x is y)") and then act accordingly - some using a shared implementation, others with dedicated logic and views.
I guess [stripped down] this would look a little like:
/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 weren't worried about future extension and maintenance and all that, we could go down the dark path and implement something like the following - which would function just fine, but would no doubt be[come] 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);
}
Another mechanism would be to use subfolders at the view layer - which would keep the code reasonably clean, but doesn't work for my situation since I want a custom action method too...
- 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);
}
Ideally, the solution would be a base controller and dedicated controllers with overrides where required - but since we have to pull the object from storage before we could determine that ideal controller, I can't figure out how to make that work...
My current ideas generally fall over the first hurdle of having the "VehicleController" know far too much about what those subtype overrides are so any ideas would be appreciated.
Cheers.