I have a complex Model
public class ComplexModel
{
public UserModel userModel;
public ExtraInfoModel extraModel;
}
where
UserModel may have required fields
as in:
public class UserModel
{
[Required]
public string email;
}
how do I validate ComplexModel to make sure that the data annotations on its member models are being taken into the account in ComplexModel validation?
Thank you.
UPDATE:
Here's my exact scenario. When I call ModelState.IsValid in a controller action on ManageProfileModel regardless of whether "SelectedValue" of ListModelRequired member of GeneralInfoModel was set or not the model state is valid.
public class ManageProfileModel
{
[Required(ErrorMessage="Experience is required")]
public int LevelOfExperienceTypeID { get; set; }
public GeneralInfoModel GeneralInfoModel { get; set; }
}
public class GeneralInfoModel
{
[Required]
[DisplayName("Profile Headline")]
public string ProfileName { get; set; }
[DisplayName("Signature")]
public string Signature { get; set; }
[Required]
public ListModelRequired LevelOfExperience { get; set; }
}
public class ListModel
{
public ListModel()
{
}
public ListModel(string name)
{
this.Name = name;
}
public ListModel(string name, string selectedValue):this(name)
{
this.SelectedValue = selectedValue;
}
public ListModel(string name, IEnumerable<SelectListItem> members):this(name)
{
this.Members = members;
}
public ListModel(string name, IEnumerable<Se开发者_开发问答lectListItem> members, string selectedValue)
: this(name, members)
{
this.SelectedValue = selectedValue;
}
public IEnumerable<SelectListItem> Members { get; set; }
public string Name { get; set; }
public virtual string SelectedValue { get; set; }
public string Label { get; set; }
}
public class ListModelRequired : ListModel
{
[Required]
public override string SelectedValue { get; set; }
public ListModelRequired():base()
{
}
public ListModelRequired(string name):base(name)
{
}
public ListModelRequired(string name, string selectedValue):base(name,selectedValue)
{
}
public ListModelRequired(string name, IEnumerable<SelectListItem> members)
: base(name, members)
{
}
public ListModelRequired(string name, IEnumerable<SelectListItem> members, string selectedValue)
: base(name, members,selectedValue)
{
}
}
I think that the default model binder gets this right, validating submodels that use the data annotations. What problem are you actually having it with it? For example, I have something similar to:
public class OnlineDonationModel
{
[Required]
public decimal? Amount { get; set; }
public ContactModel Contact { get; set; }
}
public class ContactModel
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Address { get; set; }
...
}
精彩评论