[英]Adding custom error message for model property
有没有一种方法可以覆盖控制器为模型属性抛出的默认验证错误? 例如,car.make不能为null,但是如果有人拼写错误的汽车名称,我想抛出一个特定的错误:
模型
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>
CONTROLLER
public ActionResult Create([Bind(Include = "Make,Model")] Car car)
{
ModelState.AddModelError("Car.Make", "Check your spelling");
return View(car);
}
只是您需要修改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);
}
更好的方法是将验证逻辑置于控制器之外。 而且,如果您想这样做,则需要根据验证逻辑来创建自定义注释。 要创建自定义注释,您需要创建新的类并在您的类中实现ValidationAttribute
。
public class SpellingAttributes: ValidationAttribute
{
}
下一步,您需要覆盖IsValid()
并在其中写入验证逻辑
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//validation logic
//If validation got success return ValidationResult.Success;
return ValidationResult.Success;
}
在模型类中,您可以直接使用该注释,例如
public class Car
{
public int ID { get; set; }
[Required]
[Spelling(ErrorMessage ="Invalid Spelling")
public string Make { get; set; }
}
我将实现自定义DataAnnotation
属性,并将其用于Car.Make
属性验证。
在这里,您可以了解其实现的框架:
public class CheckSpellingAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
string stringValue = value as string;
if (string.IsNullOrEmpty(stringValue) != false)
{
//your spelling validation logic here
return isSpellingCorrect(stringValue );
}
return true;
}
}
然后您可以像下面这样在模型上使用它:
public class Car
{
public int ID { get; set; }
[Required]
[CheckSpelling(ErrorMessage = "Check your spelling")]
public string Make { get; set; }
}
您的看法将不会改变,并且行动会更加简单
public ActionResult Create([Bind(Include = "Make,Model")] Car car)
{
return View(car);
}
控制器中的create方法应如下所示:
public ActionResult Create([Bind(Include = "Make,Model")] Car car)
{
if(!checkSpelling(car.Make)) {
ModelState.AddModelError("Make", "Check your spelling");
}
if (ModelState.IsValid) {
//Save changes
}
return View(car);
}
您会注意到,在您的情况下ModelState.AddModelError(string key, string errorMessage)
方法ModelState.AddModelError(string key, string errorMessage)
的第一个参数key
应该只是"Make"
。 参考: MSDN
无论如何,我建议实现类似于此示例的自定义ValidationAttribute
。
public ActionResult Create([Bind(Include = "Make,Model")] Car car)
{
if (ModelState["Make"] == null)
{
var innerModelState = new ModelState();
innerModelState.Errors.Add("Check your spelling");
ModelState.Add(new KeyValuePair<string, System.Web.Mvc.ModelState>("Make", innerModelState));
}
return View(car);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.