views:

2048

answers:

3

How do I get the collection of errors in a view?

I don't want to use the Html Helper Validation Summary or Validation Message. Instead I want to check for errors and if any display them in specific format. Also on the input controls I want to check for a specific property error and add a class to the input.

P.S. I'm using the Spark View Engine but the idea should be the same.

So I figured I could do something like...

<if condition="${ModelState.Errors.Count > 0}">
  DispalyErrorSummary()
</if>

....and also...

<input type="text" value="${Model.Name}" class="?{ModelState.Errors["Name"] != string.empty} error" />

....

Or something like that.

UPDATE

My final solution looked like this:

<input type="text" value="${ViewData.Model.Name}" class="text error?{!ViewData.ModelState.IsValid && ViewData.ModelState["Name"].Errors.Count() > 0}" id="Name" name="Name" />

This only adds the error css class if this property has an error.

+16  A: 
<% ViewData.ModelState.IsValid %>

or

<% ViewData.ModelState.Values.Any(x => x.Errors.Count > 1) %>

and for a specific property...

<% ViewData.ModelState["Property"].Errors %> // Note this returns a collection
Chad Moran
Damn! What was that like 5 seconds? Let me see if this works. thanks for the insanely quick response. You know there should be a badge for that. 'Responds to question in less than 5 seconds. And is eventually marked the correct answer.'
Ryan Montgomery
Haha, I have a bookmark just for ASP.NET MVC tag.
Chad Moran
Question - How do I get the error for a specific property?
Ryan Montgomery
the ModelState property is of dictionary typeto get the error for pass the key nameViewData.ModelState["Name"]
Marwan Aouida
It Works! Thank you.
Ryan Montgomery
A: 

Thanks Chad! To show all the errors associated with the key, here's what I came up with. For some reason the base Html.ValidationMessage helper only shows the first error associated with the key.

    <%= Html.ShowAllErrors(mykey) %>

HtmlHelper:

    public static String ShowAllErrors(this HtmlHelper helper, String key) {
        StringBuilder sb = new StringBuilder();
        if (helper.ViewData.ModelState[key] != null) {
            foreach (var e in helper.ViewData.ModelState[key].Errors) {
                TagBuilder div = new TagBuilder("div");
                div.MergeAttribute("class", "field-validation-error");
                div.SetInnerText(e.ErrorMessage);
                sb.Append(div.ToString());
            }
        }
        return sb.ToString();
    }
Rake36
A: 

To just get the errors from the ModelState, use this Linq:

var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
Chris McKenzie