7

我试图创建一个自定义 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>

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

可能是什么问题?

4

1 回答 1

8

尝试这个

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

也不要忘记检查模型状态在后面的代码中是否有效,否则它将不起作用,示例

    [HttpPost]
    public ActionResult Create(SomeObject object)
    {
        if (ModelState.IsValid)
        {
            //Insert code here
            return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }
于 2012-04-25T06:37:39.153 回答