我有一個自我驗證模型。提交表單時,錯誤不會顯示在相應文本框下方的視圖中。但是,它只顯示在ValidationSummary中。我希望它顯示在每個文本框下方。謝謝。自我驗證模型不會返回錯誤?
型號:
public class BankAccount : IValidatableObject
{
public string FirstName { get; set; }
public string LastName { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
List<ValidationResult> errors = new List<ValidationResult>();
if (string.IsNullOrEmpty(LastName))
{
errors.Add(new ValidationResult("Enter valid lastname por favor."));
}
if (string.IsNullOrEmpty(FirstName))
{
errors.Add(new ValidationResult("Enter valid firstname por favor."));
}
return errors;
}
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
BankAccount oBankAccount = new BankAccount();
return View("Home", oBankAccount);
}
[HttpPost]
public ActionResult Index(BankAccount oBankAccount)
{
return View("Home", oBankAccount);
}
}
查看:
@model BankAccountApp.Models.BankAccount
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<div>
@using (@Html.BeginForm("Index", "Home"))
{
@Html.ValidationSummary()
// FirstName TextBox
<span>FirstName: </span>
@Html.TextBoxFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
<br />
// LastName TextBox
<span>LastName: </span>
@Html.TextBoxFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName, null, new { @class = "formErrors" })
<input type="submit" value="submit me" />
}
</div>
</body>
</html>
當你標記你的'用'LastName'屬性會發生什麼[必需(的ErrorMessage = 「測試」)]'屬性? – Tejs
當我按照你說的添加必要的屬性時,如果沒有填充任何內容,它會在旁邊顯示「測試」。如果填充了內容,則不顯示任何內容。 – SaltProgrammer