Can I have a single View in a MVC project that handles multiple derived ViewModel classes? I'm currently using ASP Core RC1 targetting 4.5 .NET framework.
My derived ViewModels have specific validation implemented with data annotations. If I pass a derived model class object to the View that references the base model (@model Models.BaseModel) none of the data annotations are rendered client side with the html 5 data-val tags.
If I use strongly typed views (@model Models.ChildModel) it works as expected. I cannot use more than one @model declaration in a View so I'm unable to check the type of the model in the View and choose the type of model being rendered.
However, I want to use a shared view because there are many fields and only the validation implementation needs to change based on which derived class is being used.
Here's an example implementation:
public abstract class BaseModel
{
[Required]
public abstract string FieldTest {get; set;}
}
public class ChildModel : BaseModel
{
[Email]
public override string FieldTest {get; set;}
}
public class AnotherChildModel : BaseModel
{
[Phone]
public override string FieldTest {get; set;}
}
Here's really what I'm trying to achieve in the View:
@if(Model is ChildModel)
{
@model Models.ChildModel
}
else
{
@model Models.AnotherChildModel
}
At present time my best solution is have a separate View for each derived class view model. The problem with that is the views are merely duplications with different @model references..
