Search code examples
c#asp.net-mvcmodel-view-controllervalidationaction-filter

.NET MVC 3 How to cycle modelstate errors and force ModelState.Valid or disable specific errors?


I am using MVC 3 + unobstrusive validation.

For some field I am using remote validation too; inside remote validation, I do some checks whose can return errors or just warnings (I would like to take advantage of ajax validation just to give warnings too, not just blocking errors). I distinct the warnings by the validation errors with the "Info" prefix inside de description text.

So, does exist a way to cycle all validation errors, maintaining just warnings displayed and set errors off according the displayed text?

I was thinking of using an ActionFilterAttribute, or to force the ModelState.Valid = true after cycling and checking all the validation errors...

Here's an extract of my remote validation routine, with a WarningCheck attribute:

   [WarningCheck]
   public JsonResult CheckMyField(string myfield) 
    {

        //....some check...if ok I do `return Json(true, JsonRequestBehavior.AllowGet);`
        //...if just a warning, I do the follow...

        string warn = String.Format(CultureInfo.InvariantCulture,
            "Info: some info....");
        ModelState.AddModelError(TicketHD, esiste);
        return Json(warn, JsonRequestBehavior.AllowGet);

    }

    [AttributeUsage(AttributeTargets.All)]
    public class WarningCheckAttribute : ActionFilterAttribute
    {
      public override void OnActionExecuting(ActionExecutingContext filterContext)
       {  
             //.... here I'd like to cycle my warnings and if possible maintaining just the text display and set errors off...is it possible?
       }
     }

EDIT (how to disable client side validation for specific warnings)

Following @CDSmith (@Alfalfastrange) suggestions for server side, I succeed to disable the client side validation too, when a specific text is contained inside each validation error. In particular, my needs were to disable both client & server side validation error just when the errors contained "Info:" text. Here's the code I am using for client side behaviour:

       .... 
                    $("#ticketfrm").submit();
                    var isvalid = true;
                    var errmark = $("#ticketfrm .field-validation-error span"); 
                    $(errmark).each(function () {
                        var tst = $(this).text();
                        if (!(tst.indexOf("Info") != -1))
                            isvalid = false; //if the val error is not a warn, the it must be a real error!
                        });

                    if (isvalid) {
                        var form = $('#ticketfrm').get(0); //because I'm inside a jquery dialog
                         $.removeData(form, 'validator'); 
                        jQuery('#ticketfrm').unbind('submit').submit();
                    }

                    $("#ticketfrm").submit();   
                }
            .....

I hope this may help many people...I worked many hours to get this working! I do not think it must be the more elegant solution, but IT WORKS! :) While for server side validation, please read the marked solution.

If you find this useful, please mark it. Thank you!


Solution

  • I'm not sure I understand the question as well as you're explaining but what I hear you saying is you need a way of looping thru the ModelState errors and then maintaining the text values of the errors but not show them as errors?? Is that what you are saying?

    Well for starters, ModelState is nothing more than a DictionaryList which you can iterate through with no problem.

    Something like this can do that:

    public ActionResult SomeAction(SomeModel model) {
        if(ModelState.IsValid) {
            // do cool stuff with model data
        }
        var errorMessages = GetModelStateErrors(ModelState);
        foreach (var errorMessage in errors) {
            // do whatever you want with the error message string here
        }
    }
    

    ModelError contains an ErrorMessage property and Exception property

    internal static List<string> GetModelStateErrors(IEnumerable<KeyValuePair<string, ModelState>> modelStateDictionary) {
        var errors = new List<ModelError>();
        errors = modelStateDictionary.SelectMany(item => item.Value.Errors).ToList();
    } 
    

    Not sure if this helps or not but if it points you in the right direction then cool :-)

    Update

    Ok here is what I came up with and it works for me with my test app.

    First let me lay out what I have so you can copy and replicate

    Here's my model

    public class EmployeeViewModel {
    
        public int ID { get; set; }
    
        [Display(Name = "First Name")]
        [Required(ErrorMessage = "Error")]
        public string FirstName { get; set; }
    
        [Display(Name = "Last Name")]
        [Required(ErrorMessage = "Error")]
        public string LastName { get; set; }
    
        [Display(Name = "Username")]
        public string Username { get; set; }
    
        [Display(Name = "Email Address")]
        public string EmailAddress { get; set; }
    }
    

    Here's a simple view that uses this model

    @model TestApp.Models.EmployeeViewModel
    
    <h2>Test</h2>
    
    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)
        <fieldset>
            <legend>EmployeeViewModel</legend>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.FirstName)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.FirstName)
                @Html.ValidationMessageFor(model => model.FirstName)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.LastName)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.LastName)
                @Html.ValidationMessageFor(model => model.LastName)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Username)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Username)
                @Html.ValidationMessageFor(model => model.Username)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.EmailAddress)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.EmailAddress)
                @Html.ValidationMessageFor(model => model.EmailAddress)
            </div>
    
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    

    Here's the controller and actions that I used

    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using TestApp.Models;
    
    namespace TestApp.Controllers {
    
        public class HomeController : Controller {
    
            public ActionResult Index() {
                return RedirectToAction("Test");
            }
    
            public ActionResult Test() {
                var model = new EmployeeViewModel();
                return View(model);
            }
    
            [HttpPost]
            public ActionResult Test(EmployeeViewModel model) {
                // Force an error on this property - THIS should be the only real error that gets returned back to the view
                ModelState.AddModelError("", "Error on First Name");
    
                if(model.EmailAddress == null) // Add an INFO message
                    ModelState.AddModelError("", "Email Address Info");
                if (model.Username == null) // Add another INFO message
                    ModelState.AddModelError("", "Username Info");
    
                // Get the Real error off the ModelState
                var errors = GetRealErrors(ModelState);
    
                // clear out anything that the ModelState currently has in it's Errors collection
                foreach (var modelValue in ModelState.Values) {
                    modelValue.Errors.Clear();
                }
                // Add the real errors back on to the ModelState
                foreach (var realError in errors) {
                    ModelState.AddModelError("", realError.ErrorMessage);
                }
                return View(model);
            }
    
            private IEnumerable<ModelError> GetRealErrors(IEnumerable<KeyValuePair<string, ModelState>> modelStateDictionary) {
                var errorMessages = new List<ModelError>() ;
                foreach (var keyValuePair in modelStateDictionary) {
                    if (keyValuePair.Value.Errors.Count > 0) {
                        foreach (var error in keyValuePair.Value.Errors) {
                            if (!error.ErrorMessage.Contains("Info")) {
                                errorMessages.Add(error);
                            }
                        }
                    }
    
                }
                return errorMessages;
            }
        }
    }
    

    You can write GetRealErrors as LINQ instead if you prefer:

    private IEnumerable<ModelError> GetRealErrors(IEnumerable<KeyValuePair<string, ModelState>> modelStateDictionary) {
        var errorMessages = new List<ModelError>() ;
        foreach (var keyValuePair in modelStateDictionary.Where(keyValuePair => keyValuePair.Value.Errors.Count > 0)) {
            errorMessages.AddRange(keyValuePair.Value.Errors.Where(error => !error.ErrorMessage.Contains("Info")));
        }
        return errorMessages;
    }
    

    I hope that gives you what you were looking for, it works the way I think I understand that you wanted. Let me know