自我验证模型不返回错误

本文关键字:返回 错误 模型 验证 自我 | 更新日期: 2023-09-27 18:06:28

我有一个自我验证模型。提交表单时,错误不会显示在相应文本框下面的视图中。然而,它只显示在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>

自我验证模型不返回错误

按如下方式更改方法

  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" });
    }
  }

听起来您制作验证模型的方法已经过时了。我建议使用DataAnnotations方法对模型进行验证。这似乎行得通。