您可以编写自定义验证属性:
public class RequiredIfAttribute : ValidationAttribute
{
public RequiredIfAttribute(string otherProperty, object otherPropertyValue)
{
OtherProperty = otherProperty;
OtherPropertyValue = otherPropertyValue;
}
public string OtherProperty { get; private set; }
public object OtherPropertyValue { get; private set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(OtherProperty);
if (property == null)
{
return new ValidationResult(string.Format("Unknown property: {0}", OtherProperty));
}
object otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);
if (!object.Equals(OtherPropertyValue, otherPropertyValue))
{
return null;
}
if (value != null)
{
return null;
}
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
}
现在你可以有一个视图模型:
public class MyViewModel
{
public string Country { get; set; }
[RequiredIf("Country", "usa", ErrorMessage = "Please select a state")]
public string State { get; set; }
public IEnumerable<SelectListItem> Countries
{
get
{
return new[]
{
new SelectListItem { Value = "fr", Text = "France" },
new SelectListItem { Value = "usa", Text = "United States" },
new SelectListItem { Value = "spa", Text = "Spain" },
};
}
}
public IEnumerable<SelectListItem> States
{
get
{
return new[]
{
new SelectListItem { Value = "al", Text = "Alabama" },
new SelectListItem { Value = "ak", Text = "Alaska" },
new SelectListItem { Value = "az", Text = "Arizona" },
};
}
}
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
和一个观点:
@model MyViewModel
@using (Html.BeginForm())
{
<div>
@Html.DropDownListFor(x => x.Country, Model.Countries, "-- Country --")
@Html.ValidationMessageFor(x => x.Country)
</div>
<div>
@Html.DropDownListFor(x => x.State, Model.States, "-- State --")
@Html.ValidationMessageFor(x => x.State)
</div>
<button type="submit">OK</button>
}
您可能还会发现Foolproof验证属性包很有用。