Self-Validating Model Not Returning Errors?
I have a self validating model. When the form is submitted, the errors don't show up in the view underneath their corresponding textboxes. However, it only shows up in the ValidationSummary. I want it to show up underneath each textbox. Thanks.
Model:
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;
}
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
BankAccount oBankAccount = new BankAccount();
return View("Home", oBankAccount);
}
[HttpPost]
pu开发者_Go百科blic ActionResult Index(BankAccount oBankAccount)
{
return View("Home", oBankAccount);
}
}
View:
@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>
change you method as following
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrEmpty(LastName))
{
yield return new ValidationResult("Enter valid lastname por favor", new[] { "LastName" });
}
if (string.IsNullOrEmpty(FirstName))
{
yield return new ValidationResult("Enter valid firstname por favor.", new[] { "FirstName" });
}
}
It sounds like your method for making a validated model has been obsoleted. I would suggest moving to the DataAnnotations method for making validation on your models. That seems to work.
精彩评论