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");
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();
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With