自定义ValidationAttribute不起作用

时间:2012-04-25 06:12:48

标签: c# asp.net-mvc-3 validationattribute

我尝试创建自定义ValidationAttribute:

public class RollType : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return false;   // just for trying...
    }
}

然后我创建了(在另一个类中) -

  [RollType]
  [Range(0,4)]
  public int? Try { get; set; }

在视图上(我使用MVC)我写道:

      <div class="editor-label">
            Try:
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Try)
            @Html.ValidationMessageFor(model => model.Try)
        </div>

“范围”的验证效果很好,但不适用于自定义的验证!

可能是什么问题?

1 个答案:

答案 0 :(得分:7)

试试这个

public class RollType : ValidationAttribute
{
   protected override ValidationResult IsValid(object value, ValidationContext validationContext)
   {
      return new ValidationResult("Something went wrong");
   }
}

另外,不要忘记检查modelstate在后面的代码中是否有效,否则它将无效,例如

    [HttpPost]
    public ActionResult Create(SomeObject object)
    {
        if (ModelState.IsValid)
        {
            //Insert code here
            return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }