Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

asp.net-mvc

I'm 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 looks like this:

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 can't use currentPage.Validators. I need to use ModelState but my problem is that I can't access ModelState when I'm not in the Controller. I tried accessing the controller or the ModelState via HttpContext but I've not found a way to do it. Any idea ?

ModelState.AddModelError("", "My error message");
like image 201
JP Tétreault Avatar asked Oct 18 '22 13:10

JP Tétreault


1 Answers

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 around like this:

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

Use in controller:

MyClass.errorMessage(ModelState);

Use in view:

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 help from this and this links.

like image 84
Ashiquzzaman Avatar answered Oct 21 '22 04:10

Ashiquzzaman