我尝试创建一个自定义的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>对"range“的验证效果很好,但不适用于自定义验证!
会有什么问题呢?
发布于 2012-04-25 14:37:39
尝尝这个
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();
}
}https://stackoverflow.com/questions/10310255
复制相似问题