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

Go To StackoverFlow.com

2

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>
2012-04-04 05:12
by stuartdotnet
Why don't you use @Html.ErrorMessageFor(model => model.Name) method to render the error message in your view? If you put this into a div, then you can add styles as well, using that div - Lasantha Bandara 2012-04-04 05:24
I could do this but unfortunately the project requires me to change the label text, and besides regardless of which helper method I use this still this doesn't answer the question of HOW to change the css.. - stuartdotnet 2012-04-04 05:27


1

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 "";
    }
2012-07-19 14:16
by Mike_W


0

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.

2012-04-04 07:47
by TRR
This doesn't work for so many reasons. Where do you put this code? In the Validate method - stuartdotnet 2012-04-04 23:03
you can set it when the validation message is se - TRR 2012-04-05 07:27
So then what do you do with oppdesc? How do you make it style your control? Because in MVC the property isn't actually a control - stuartdotnet 2012-04-10 22:43
@Html.LabelFor(model => model.oppdesc)
@Html.EditorFor(model => model.oppdesc)

where oppdesc is a property in your mode - TRR 2012-04-11 12:43
But this is only changing the value of the property, the view does not display a property by simply referencing its value - stuartdotnet 2012-04-12 03:02
Ads