I would not recommend doing this because the view is related to the model. I expect that you have two very similar models for this, but you still have to create different conditions around the properties that are in one model and not in another, along with a problem that can change the problem of one area.
You can do this if both models inherit from the same base:
public class ModelBase { public string SharedProperty { get; set; } } public class ModelA : ModelBase { public string AProp { get; set; } } public class ModelB : ModelBase { public string BProp { get; set; } }
Then, in your view, use the base for the model and bring it to where necessary:
@model ModelBase @if (Model.GetType() == typeof(ModelA)) { @Html.EditorFor(m => ((ModelA)m).AProp) }
You also need to accept the ModelBase and drop it into the controller:
public ActionResult SomeAction(ModelBase model) { bool modA = model.GetType() == typeof(ModelA); string a = modA ? ((ModelA)model).PropA : ""; }
But then again, this will lead to messy code!
Steve harris
source share