【问题标题】:Custom ValidationAttribute doesn't work自定义 ValidationAttribute 不起作用
【发布时间】:2012-05-05 19:38:28
【问题描述】:

我尝试创建自定义 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>

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

可能是什么问题?

【问题讨论】:

  • 请注意,RollTypeAttribute 是此类的推荐名称。您仍然可以将 [RollType] 与该新名称一起使用。

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


【解决方案1】:

试试这个

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

【讨论】:

  • “错误 1 ​​'RollType.IsValid(object, System.ComponentModel.DataAnnotations.ValidationContext)': 覆盖'protected'继承成员'System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(对象,System.ComponentModel.DataAnnotations.ValidationContext)' "
  • 对不起,我刚刚修复了错误,它需要保护覆盖而不是公共覆盖,它现在可以工作了。
  • 另外,如果您想发送成功消息,请使用 'return ValidationResult.Success;'
  • 谢谢!我删除了我所做的一切并从头开始使用您的代码,现在它可以工作了.. :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
  • 1970-01-01
  • 2020-05-21
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多