开发者

Create custom error programmatically for MVC

开发者 https://www.devze.com 2023-03-06 23:18 出处:网络
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 th

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....
}  
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号