为模型属性添加自定义错误消息 [英] Adding custom error message for model property

查看:66
本文介绍了为模型属性添加自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以覆盖控制器为模型属性抛出的默认验证错误?例如,car.make不能为null,但是如果有人拼写错误的汽车名称,我想抛出一个特定错误.

Is there a way I can override the default validation error that is thrown up for a model property from the controller? For example, the car.make cannot be null, but I want to throw a specific error if the person spells the name of the car make wrong.:

模型

public class Car
{
    public int ID { get; set; }
    [Required]
    public string Make { get; set; }
}

查看

<div class="form-group">
       @Html.EditorFor(model => model.Make, new { htmlAttributes = new { @class = "form-control" } })
       @Html.ValidationMessageFor(model => model.Make, "", new { @class = "text-danger" })
</div>

控制器

public ActionResult Create([Bind(Include = "Make,Model")] Car car)
{
    ModelState.AddModelError("Car.Make", "Check your spelling");
    return View(car);
}

推荐答案

只需修改 ModelState.AddModelError("Car.Make",检查拼写"); 方法,如

public ActionResult Create([Bind(Include = "Make,Model")] Car car)
{
     if(//Your Condition upon which you want to model validation throw error) {
        ModelState.AddModelError("Make", "Check your spelling");
      }
     if (ModelState.IsValid) {
       //Rest of your logic 
     }
   return View(car);
 }

更好的方法是将验证逻辑置于控制器之外.如果要这样做,则需要根据验证逻辑创建自定义注释.要创建自定义注释,您需要创建新的类并在您的类中实现 ValidationAttribute .

Better approach is to keep the validation logic out of the controller. And if you want to do that you need to create you custom annotation based on your validation logic. To Create a custom annotation you need to create new class and implement the ValidationAttribute in your class.

 public class SpellingAttributes: ValidationAttribute  
 {
 } 

下一步,您需要覆盖 IsValid()并在其中编写验证逻辑

Next step you need to override the IsValid() and write you validation logic inside that

protected override ValidationResult IsValid(object value, ValidationContext validationContext)  
{  
    //validation logic 

   //If validation got success return ValidationResult.Success;
    return ValidationResult.Success;  
} 

在模型类中,您可以直接使用该注释,例如

And In your model class you can directly use this annotation like

public class Car
{
     public int ID { get; set; }
     [Required]
     [Spelling(ErrorMessage ="Invalid Spelling")
     public string Make { get; set; }
}

有关如何在MVC中创建自定义注释的更多详细信息,请参阅我的

For more details about how to create a custom annotation in MVC you can refer my blog here Hope it helps you.

这篇关于为模型属性添加自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆