Reputation: 41
I need to bind different model to same view according to some condition. Then Can I change model of view in runtime.
Upvotes: 1
Views: 872
Reputation: 5109
I wouldn't really recommend doing this as a view is coupled to the model. I expect you have two very similar models for this but you're still going to need to put in various conditions around properties that are in one model and not the other along with the issue that modifying this view can potentially cause a problem for more than one area.
You can do this if both your 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 cast where needed:
@model ModelBase
@if (Model.GetType() == typeof(ModelA))
{
@Html.EditorFor(m => ((ModelA)m).AProp)
}
You will also need to accept ModelBase and cast in the controller:
public ActionResult SomeAction(ModelBase model)
{
bool modA = model.GetType() == typeof(ModelA);
string a = modA ? ((ModelA)model).PropA : "";
}
But again, this will lead to messy code!
Upvotes: 2