有没有办法可以覆盖从控制器为模型属性抛出的默认验证错误?例如,car.make不能为空,但如果该人拼写汽车名称出错,我想抛出一个特定的错误。:
MODEL
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);
}
答案 0 :(得分:5)
您需要修改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; }
}
有关如何在MVC中创建自定义注释的更多详细信息,您可以参考我的blog here希望它可以帮助您。
答案 1 :(得分:1)
我会实现自定义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);
}
答案 2 :(得分:0)
控制器中的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);
}
您会注意到方法key
的第一个参数ModelState.AddModelError(string key, string errorMessage)
在您的情况下应该只是"Make"
。参考:MSDN
无论如何,我建议您实施类似于this example的自定义ValidationAttribute
。
答案 3 :(得分:0)
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);
}