stuartdotnet
stuartdotnet

Reputation: 3034

How to add css to a single mvc Helper method when validation fails - from within the model

Does anyone have a simple way of adding a css class to a html label when validation fails, preferably from within the model, in the public IEnumerable Validate(ValidationContext context) override, not with jQuery or in the Controller.

I have my validationsummary giving me the error message I just want to put * next to the failed input and make its label text bold and red.

    @Html.LabelFor(model => model.Name)
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)<br/><br />
    </div>

Upvotes: 2

Views: 899

Answers (2)

Mike_W
Mike_W

Reputation: 26

If you have not yet found a solution, look at http://weblogs.asp.net/imranbaloch/archive/2010/07/03/asp-net-mvc-labelfor-helper-with-htmlattributes.aspx

It codes an HTML Helper extension to LabelFor that supports html attributes. You could use this code as a template to modify for your needs. One option would be to detect whether a validation error has occured. A few days ago I wrote something similar:

    public static string IsInvalidFor<TModel, TValue>(
        this HtmlHelper<TModel> htmlHelper,            
        Expression<Func<TModel, TValue>> expression, 
        string cssErrorClass)
    {
        if (ValidationExtensions.ValidationMessageFor(htmlHelper, expression) != null) 
             return cssErrorClass;
        else return "";
    }

Upvotes: 1

TRR
TRR

Reputation: 1643

if you want to do it in .cs file Model in this case just append this

            string name = //ur name property//;
            oppdesc = "";               
            oppdesc += "<span class ="error"+ "\">" +      name+ "</span>";

and u define class error as bold and red in ur css.

Upvotes: 0

Related Questions