Jesse Hallam
Jesse Hallam

Reputation: 6964

Is manipulating the ModelState in this way a coding mispractice?

I am presented with a situation where I would like to use Html.ValidationSummary() in my views to display a generic error message. Maybe something like "There was a problem with the information you entered." but without getting a list of every single thing that went wrong (as per DataAnnotations).

side note: I've found references to people using if(ViewContext.ViewData.ModelState.IsValid){ ... } in their views and foregoing ValidationSummary altogether. I am not really impressed with that approach, to say the least.

It's important that the ModelStateDictionary still contains a key for each model element which had a validation error (so that Html.EditorFor, et al. write the correct css classes.)

What I ended up with and seems to work is:

public static class ModelStateHelpers
{
    public static void Empty(this ModelStateDictionary @this)
    {
        foreach (KeyValuePair<string, ModelState> state in @this)
        {
            if (state.Value.Errors.Any())
            {
                state.Value.Errors.Clear();
                state.Value.Errors.Add(String.Empty);
            }
        }
    }
}

Followed by this in my class:

if (StuffWentWrong) {
    this.ModelState.Empty();
    this.ModelState.AddModelError("", "Something went wrong...");
}

As intended, the Html.ValidationSummary is smart enough to suppress html structure for ModelStates in the dictionary whose error messages are blank; and I also end up with text fields decorated with error validation attributes, such as <input class="input-validation-error text-box single-line" data-val="true" data-val-required="The User Name field is required." id="UserName" name="UserName" type="text" value="" />

Does this particular solution smell badly?

Upvotes: 0

Views: 563

Answers (1)

danludwig
danludwig

Reputation: 47375

I've found references to people using if(ViewContext.ViewData.ModelState.IsValid){ ... } in their views and foregoing ValidationSummary altogether. I am not really impressed with that approach, to say the least.

Why not? I think this is a reasonable solution. You say you want a special use case for displaying the validation summary, which is a view concern. You shouldn't have to manipulate anything in the controller or otherwise fight the framework to accomplish this.

As to whether or not your current solution with a static helper class + method, I think that smells worse than checking ViewContext.ViewData.ModelState.IsValid from razor. I commented that you should download the source code for the ValidationSummary HtmlHelper and look into retooling it to suit your needs, which is probably the best answer to your question. You could essentially encapsulate the aforementioned if statement into a custom HtmlHelper, which is an appropriate place to put code for view concerns.

Upvotes: 1

Related Questions