繼我以前回答問題的意見稍有分歧,在評論該數據現在是user1079925聲明以單一模式提供。因此,我已經爲這種單一模型方法提供了使用自定義數據註釋的替代解決方案(以前的答案將被刪除):
此示例假定用戶將輸入名字,中間名和姓氏。如果輸入中間名或姓氏中的任何一個,則必須輸入姓氏。
型號:
public class IndexModel
{
[RequiredIfOtherFieldEntered("MiddleName", "Surname", ErrorMessage="Please enter the forename")]
public string Forename { get; set; }
public string MiddleName { get; set; }
public string Surname { get; set; }
}
IndexView:
@model MvcApplication6.Models.IndexModel
<h2>Index</h2>
@using (Html.BeginForm())
{
<p>Forename: @Html.EditorFor(m => m.Forename) @Html.ValidationMessageFor(m => m.Forename)</p>
<p>If you enter the middle name or the surname then the forename will be required.</p>
<p>Middlename: @Html.EditorFor(m => m.MiddleName)</p>
<p>Surname: @Html.EditorFor(m => m.Surname)</p>
<input type="submit" value="submit"/>
}
HomeController中:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(IndexModel indexModel)
{
if (ModelState.IsValid)
{
return RedirectToAction("NextPage");
}
else
{
return View();
}
}
}
CustomAttribute:
public class RequiredIfOtherFieldEnteredAttribute : ValidationAttribute
{
private string[] properties;
public RequiredIfOtherFieldEnteredAttribute(params string[] properties)
{
if (properties == null && properties.Length < 1)
{
throw new ArgumentNullException("properties");
}
this.properties = properties;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
foreach (string property in properties)
{
//using System.Reflection.PropertyInfo;
PropertyInfo propertyInfo = validationContext.ObjectType.GetProperty(property);
if (propertyInfo == null)
{
return new ValidationResult(string.Format("Property '{0}' is undefined.", property));
}
var propertyValue = propertyInfo.GetValue(validationContext.ObjectInstance, null);
if (propertyValue != null && !string.IsNullOrEmpty(propertyValue.ToString()))
{
if (value == null || string.IsNullOrEmpty(value.ToString()))
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
}
return null;
}
}
謝謝 - 我會研究一下 – user1079925