I want to create a model-view-controller without having if-else for individual controls, or having to duplicate these to handle different on-screen controls.
Currently I have:-
//controller
public ActionResult DisplayThing1(int thingType, string thingName){
Thing1Model model = new Thing1Model();
return View(model);
}
[HttpPost]
public ActionResult DisplayThing1(Thing1Model model)
{
Save(model);
return RedirectToAction("DisplayThing1");
}
// model
public class Thing1Model()
{
public int type {get; set; }
public string Name {get; set;}
}
// view
@using(Html.BeginForm(....))
{
@Html.HiddenFor(m=>m.type);
@Html.LabelForI(m=>m.Name);
}
I have pretty much duplicated controller for Thing2Model
, the model itself is
public class Thing2Model()
{
public int type {get; set; }
public string Name {get; set;}
public DateTime MyDate {get; set;}
}
A combined view would look like the following.
@using(Html.BeginForm(....))
{
@Html.HiddenFor(m=>m.type);
@Html.LabelForI(m=>m.Name);
@if(type == "2")
{
@Html.TextBoxFor(m=>m.MyDate);
}
}
I am looking for a better option to avoid @if
as well as duplicated code
EDIT: Adding onto @W92 answer. We also need to change the model binder to support inherited models. Otherwise, in the the view for this code, MVC won't understand how to put child properties.