the*_*eld 2 c# forms validation asp.net-mvc
有没有办法可以覆盖从控制器为模型属性抛出的默认验证错误?例如,car.make不能为null,但如果该人拼写汽车名称错误,我想抛出一个特定的错误:
模型
public class Car
{
public int ID { get; set; }
[Required]
public string Make { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
视图
<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>
Run Code Online (Sandbox Code Playgroud)
CONTROLLER
public ActionResult Create([Bind(Include = "Make,Model")] Car car)
{
ModelState.AddModelError("Car.Make", "Check your spelling");
return View(car);
}
Run Code Online (Sandbox Code Playgroud)
只需要修改ModelState.AddModelError("Car.Make", "Check your spelling");方法就好了
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);
}
Run Code Online (Sandbox Code Playgroud)
更好的方法是将验证逻辑保持在控制器之外.如果您想这样做,您需要根据验证逻辑创建自定义注释.要创建自定义注释,您需要创建新类并ValidationAttribute在类中实现.
public class SpellingAttributes: ValidationAttribute
{
}
Run Code Online (Sandbox Code Playgroud)
下一步,您需要覆盖IsValid()并在其中写入验证逻辑
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//validation logic
//If validation got success return ValidationResult.Success;
return ValidationResult.Success;
}
Run Code Online (Sandbox Code Playgroud)
在您的模型类中,您可以直接使用此注释
public class Car
{
public int ID { get; set; }
[Required]
[Spelling(ErrorMessage ="Invalid Spelling")
public string Make { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
有关如何在MVC中创建自定义注释的更多详细信息,您可以在此处参考我的博客希望它可以帮助您.