With ASP.NET MVC, how to display errors when an external controller?

I am trying to easily display errors in my view from anywhere in my code using:

@Html.ValidationSummary("", new { @class = "text-danger" }) 

Before MVC, I used:

 ValidationError.Display("My error message"); 

And my ValidationError class is as follows:

 public class ValidationError : IValidator { private ValidationError(string message) { ErrorMessage = message; IsValid = false; } public string ErrorMessage { get; set; } public bool IsValid { get; set; } public void Validate() { // no action required } public static void Display(string message) { // here is the only part I would like to change ideally var currentPage = HttpContext.Current.Handler as Page; currentPage.Validators.Add(new ValidationError(message)); } } 

Now with MVC, to add errors, I cannot use currentPage.Validators . I need to use ModelState , but my problem is that I cannot access the ModelState when I am not in the controller . I tried to access the controller or ModelState through the HttpContext , but I did not find a way to do this. Any idea?

 ModelState.AddModelError("", "My error message"); 
+5
source share
1 answer

1. You can access it through ViewContext.ViewData.ModelState . Then use

 @if (!ViewContext.ViewData.ModelState.IsValid) { <div>There are some errors</div> } 

OR

 ViewData.ModelState.IsValidField("NameOfInput") 

get a list of inputs:

 var errors = ViewData.ModelState.Where(n => n.Value.Errors.Count > 0).ToList(); 

2. You can pass your model state something like this:

 public class MyClass{ public static void errorMessage(ModelStateDictionary ModelState) { if (something) ModelState.AddModelError("", "Error Message"); } } 

Use in the controller:

 MyClass.errorMessage(ModelState); 

Use in sight:

 MyClass.errorMessage(ViewContext.ViewData.ModelState.IsValid); 

3. ModelState via ActionFilter

 public class ValidateModelAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.Controller.ViewData.ModelState.IsValid) { //Do Something } } } 

You can get more information from this and these links.

+2
source

All Articles