gpt4 book ai didi

c# - 为模型属性添加自定义错误消息

转载 作者:行者123 更新时间:2023-11-30 20:19:54 24 4
gpt4 key购买 nike

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

型号

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

更好的方法是将验证逻辑放在 Controller 之外。如果你想这样做,你需要根据你的验证逻辑创建自定义注释。要创建自定义注释,您需要创建新类并在您的类中实现 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; }
}

有关如何在 MVC 中创建自定义注释的更多详细信息,您可以引用我的 blog here希望对你有帮助。

关于c# - 为模型属性添加自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37801718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com