I have two models that only differ by what fields are required, and I would like to be able to use the same view to display both of them.
I have a UserEdit class
public abstract class UserEdit
{
public User User { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[EqualTo("NewPassword")]
public string ConfirmPassword { get; set; }
}
and a UserCreate Class that adds the required attribute to the NewPassword and ConfirmPassword properties.
class UserCreate_Metadata
{
[Required]
public string NewPassword { get; set; }
[Required]
public string ConfirmPassword { get; set; }
}
[MetadataType(typeof(UserCreate_Metadata))]
public partial class UserCreate : UserEdit
{
}
Both of these work fine in the view if I bind the model to the specific class like so:
@model Siaa.NextWeb.Data.UserEdit
or
@model Siaa.NextWeb.Data.UserCreate
Is there a way to make the view detect which class it is binding to so that it picks up the extra validation requirement of the UserCreate class? I tried using a dynamic view, but receive a “expression tree may not contain a dynamic operation” which research has pointed me to the lambda expressions used to create the editors
@Html.EditorFor(model => model.User.FirstName)
The most intuitive way to do this would be to combine both models onto a single model that you always pass to the view. Then simply add some sort of flag on to the model that determines which one you should use.
Then in your view: