我有一个具有两种模型的视图:通用帐户e个人资料用户。
public class AccountModel
{
[Display(Name = "UserId", Prompt = "UserId", ResourceType = typeof(Strings))]
public string UserId { get; set; }
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(Validation))]
[EmailAddress(ErrorMessage = null, ErrorMessageResourceName = "InvalidEmail", ErrorMessageResourceType = typeof(Validation))]
[Display(Name = "Email", Prompt = "Email", ResourceType = typeof(Strings))]
public string Email { get; set; }
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(Validation))]
[StringLength(100, ErrorMessageResourceName = "FieldMaximumLength", ErrorMessageResourceType = typeof(Validation))]
[Display(Name = "DisplayName", Prompt = "DisplayName", ResourceType = typeof(Strings))]
public string DisplayName { get; set; }
[Display(Name = "PhoneNumber", Prompt = "PhoneNumber", ResourceType = typeof(Strings))]
public string PhoneNumber { get; set; }
[Display(Name = "Country", Prompt = "Country", ResourceType = typeof(Strings))]
public int CountryId { get; set; }
public SelectList CountryList { get; set; }
}
public class UserProfileModel
{
[Display(Name = "ID User", Prompt = "ID User")]
public string IDUser { get; set; }
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(Validation))]
[StringLength(100, ErrorMessageResourceName = "FieldMaximumLength", ErrorMessageResourceType = typeof(Validation))]
[Display(Name = "UserFullName", Prompt = "UserFullName")]
public string UserFullName { get; set; }
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(Validation))]
[StringLength(16, ErrorMessageResourceName = "FieldMaximumLength", ErrorMessageResourceType = typeof(Validation))]
[Display(Name = "Code", Prompt = "Code")]
public string Code { get; set; }
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(Validation))]
[StringLength(250, ErrorMessageResourceName = "FieldMaximumLength", ErrorMessageResourceType = typeof(Validation))]
[Display(Name = "Birth Place", Prompt = "BirthPlace")]
public string BirthPlace { get; set; }
[Display(Name = "Newsletter")]
public bool? Newsletter { get; set; }
[Display(Name = "Avatar", Prompt = "Avatar")]
public string Avatar { get; set; }
}
仅当至少一个与他相关的领域被填写时,我才应验证第二个模型。
例如,如果输入BirthPlace
,则还要验证第二个模型,否则仅验证第一个模型。
希望我的要求明确
答案 0 :(得分:0)
如果我理解您的问题,可能您想知道如何手动验证模型。
您可以使用TryValidateModel(modelInstance);
调用来手动验证所需的模型。
对于问题中提到的其他条件,可以添加if语句。
例如如果userProfileModelObject的所有字符串属性均为NULL,则验证accountModelInstance
bool isSecondObjectValid = userProfileModelObject.GetType().GetProperties()
.Where(pi => pi.PropertyType == typeof(string))
.Select(pi => (string)pi.GetValue(myObject))
.Any(value => string.IsNullOrEmpty(value));
bool validationResult = false;
validationResult = !isSecondObjectValid ?
TryValidateModel(accountModelInstance) :
TryValidateModel(userProfileModelObject);
我希望这会有所帮助。
参考: