自我验证模型没有返回错误?

时间:2011-08-24 16:01:05

标签: c# asp.net asp.net-mvc razor

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

2 个答案:

答案 0 :(得分:3)

按以下方式更改方法

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

答案 1 :(得分:0)

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