Create custom error programmatically for MVC
I'm using a third party component that I call a method passing a model object and if it finds any error, it will call a callback method passing an array of ValidationResult. What I wanna do is set those errors so that Html.TextBoxFor will render the attribute class="input-validation-error".
At the moment, I decorate my model class with the v开发者_Python百科alidation attributes that I need, and if the Name is empty, it works as expected, and make the Name input red, but if the component says it's invalid for any reason, I have a new foreach loop that will print the error messages...
I want to do something inside this callback method that will make my view work just like as if I had decorated my model class with the validation attributes...
Is this possible?
You can use ModelState.AddModelError(string, string) inside the controller.
// .. the model
public class MyModel { public string Property { get; set; } }
// .. in the controller
public ActionResult DoSomething(MyModel x)
{
if(x.Property == "2")
{
ModelState.AddModelError("Property", "2 is not allowed");
return View("EditorView", x);
}
// else....
}
精彩评论