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>
2
  • 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. Commented Apr 4, 2012 at 5: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..? Commented Apr 4, 2012 at 5:27

2 Answers 2

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 "";
    }
Sign up to request clarification or add additional context in comments.

Comments

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.

5 Comments

This doesn't work for so many reasons. Where do you put this code? In the Validate method?
you can set it when the validation message is set
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.
@Html.LabelFor(model => model.oppdesc) <div class="editor-field"> @Html.EditorFor(model => model.oppdesc)<br/><br /> </div> where oppdesc is a property in your model
But this is only changing the value of the property, the view does not display a property by simply referencing its value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.