tags:

views:

134

answers:

3

When using a Html.EditorFor and passing in my ViewModel is it possible to not have each individual form element display their error message.

I'm using the validation summary and as such the error messages are showing up twice. Once for the form element and then again in the summary.

A: 

Checkout this article to find out how to customize Html.EditorFor templates.

Darin Dimitrov
I am specifically using EditorFor a generic model without a template.
Detroitpro
A: 

You can remove the individual errors by removing the error message from the ValidationMessage by using "*" as in the example below. If you however have an error message passed then it will be displayed.

<%= Html.ValidationMessage("PropertyName", "*") %>

If you however have an error message passed then it will be displayed. This is also true for the Editor templates or using the new lambda version of Html.Helper as shown below

Html.ValidationMessageFor(m=>m.prop,...)

Hope that helped,

Eddy

Dax70
A: 

You can create a custom validation summary and add all your errors with a special key (in this example i use _FORM. For example :

        private const string VALIDATIONSUMMARY_HMTL = "<div class=\"input-validation-error\">{0}</div>";

public static string ValidationSummary(this HtmlHelper helper, bool customErrorOnly)
    {
        return ValidationSummary(helper, customErrorOnly, "_FORM");   
    }

    public static string ValidationSummary(this HtmlHelper helper, bool customErrorOnly, string errorName)
    {
        if (helper.ViewData.ModelState.IsValid)
        {
            return null;
        }

        string list = "<ul>";
        bool displayList = false;
        foreach (KeyValuePair<string, ModelState> pair in helper.ViewData.ModelState)
        {
            foreach (ModelError error in pair.Value.Errors)
            {
                if (pair.Key.ToUpper() == "_FORM" || !customErrorOnly)
                {
                    list += "<li>" + error.ErrorMessage + "</li>";
                    displayList = true;
                }
            }
        }
        list += "</ul>";

        if (!displayList)
        {
            return null;
        }

        return string.Format(VALIDATIONSUMMARY_HMTL, list);
    }

When you want to add a specific error :

ViewData.ModelState.AddModelError("_FORM", "My error message");
Guillaume Roy