I am trying to create a view model for editing which contains some slightly different fields then the main model, however it appears when trying to render a view for this view model it throws and exception because some properties are missing that are specified in the MetadataType.
Code:
[MetadataType(typeof(IAdministrator))]
public partial class Administrator : IAdministrator
{
public string Name { get { return String.Format("{0} {1}", FirstName, LastName); } }
}
[MetadataType(typeof(IAdministrator))]
public class AdministratorEdit
{
public int AdministratorID { get; set; }
public string EmailAddress { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[DisplayName("New Password")]
[DataType(DataType.Password)]
[StringLength(12, MinimumLength = 8)]
public string NewPassword { get; set; }
[DisplayName("Re-New Password")]
[DataType(DataType.Password)]
[StringLength(12, MinimumLength = 8)]
public string ReNewPassword { get; set; }
}
public interface IAdministrator
{
[Required]
[DisplayName("Email Address")]
[DataType(DataType.EmailAddress)]
[RegularExpression(@"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$")]
[StringLength(320)]
string EmailAddress { get; set; }
[Required]
[DisplayName("Password")]
[Data开发者_运维知识库Type(DataType.Password)]
[StringLength(12, MinimumLength = 8)]
string Password { get; set; }
[Required]
[DisplayName("First Name")]
[DataType(DataType.Text)]
[StringLength(25)]
string FirstName { get; set; }
[Required]
[DisplayName("Last Name")]
[DataType(DataType.Text)]
[StringLength(25)]
string LastName { get; set; }
[DisplayName("Date Created")]
[DataType(DataType.Date)]
DateTime Date { get; set; }
}
This is the exception that I get from the view which uses the AdministratorEdit model: The associated metadata type for type '....Models.AdministratorEdit' contains the following unknown properties or fields: Password, Date. Please make sure that the names of these members match the names of the properties on the main type.
Can someone please sugest another method of creating a view model without having to specify another MetadataType or just a quick fix for this exception?
From your IAdminstrator interface you could extract a base class (interface), the base interface would just have the edit fields (IAdministratorEdit) and IAdministrator would remain with all fields, as it would inherit from the IAdministratorEdit.
public interface IAdministrator : IAdministratorEdit
and then just use the IAdministratorEdit interface on your ViewModel. That way you only have to define the constraints in you metadata once.
精彩评论