3

I have a textboxfor control on my razor view:

@Html.TextBoxFor(model => model.PrimaryAddressLine1)

If the user leaves this field blank the validation will add class="input-validation-error" to the field changing its color to red (as expected). However if i try to add a custom css class to the field like so:

@Html.TextBoxFor(model => model.PrimaryAddressLine1, new { @Class = "addressfield" })

I loose the red color as the "input-validation-error" class is no longer added to the control.

How can i keep the red color and add my custom css class?

5
  • I'm not sure if it matters, but typically @class would be lowercased. Commented Jun 5, 2014 at 20:01
  • how about adding color=red in the addressfield class to be sure? :) Commented Jun 5, 2014 at 20:31
  • are you trying to implement the conditional validation over there? Commented Jun 5, 2014 at 21:29
  • How are you adding the validation message? are you using @Html.ValidationMessageFor(model => model.PrimaryAddressLine1). And this is happening because you a using your own class so if you want to keep the color just add background-color:red to your addressfield class or remove your addressfield class and just add @Html.TextBoxFor(model => model.PrimaryAddressLine1, new { style = "any styles you want" }) this will not override the input-validation-error class Commented Jun 6, 2014 at 1:12
  • Moises: I dont want to use a style attribute as i have several fields all with the same style and i would expect to style them all with a css class. I dont want to add a validation message next to each field as it wont work with my design i use a validation summary at the top of the page. gardarvalur: if i just add color=red the field will always be red! i only want red when there is a validation error. Erik: it didn't make a difference Commented Jun 6, 2014 at 14:43

4 Answers 4

2

Change the @Class to @class. That did the trick for me.

@Html.TextBoxFor(model => model.PrimaryAddressLine1, new { @class = "addressfield" })
Sign up to request clarification or add additional context in comments.

3 Comments

Nice find. For some reason I seem to always use uppercase Class and never realized it made a difference until now. Lower case class worked great for this, thanks.
Remember to mark it as the answer if it solved your problem :)
I wish I could, I wasn't the original poster unfortunately. Sorry.
1

add validatorfor below the textbox line like below

 <div class="form-group">
            @Html.LabelFor(c => c.CompanyName, new { @class = "col-md-2 control-label" })
            <div class="col-sm-10 ">
                @Html.TextBoxFor(c=>c.CompanyName, new { @class = "form-control" })
                @Html.ValidationMessageFor(c => c.CompanyName, "", new { @style="color:blue;"})
            </div>
        </div>

and output will like this

enter image description here

1 Comment

I don't want to add validation messages next to each field as it wont work with the design of my application. I want the field to have a given style but if there is a validation error change the field to red.
1

While the ValidationMessageFor option is suitable in most cases i don't actually want a message next to the field. I use a ValidationSummary at the top of the page to list the errors. Adding a style attribute is also acceptable however i have several fields and i want to set the style on all of them to match and css would be the way i would expect to achieve this.

I've created a custom textboxfor which allows me to specify if the field is "locked" or "unlocked" I've made a few changes to make it add the validation class if there is a fault with the field while keeping any custom css classes.

    public static MvcHtmlString LockableTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes, bool locked)
    {
        string fullName = ExpressionHelper.GetExpressionText(expression);

        // Convert htmlAttributes into a dictionary
        RouteValueDictionary dic = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

        // Get the validation attributes
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);            
        IDictionary<string, object> validationAttributes = helper
            .GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata);

        // Merge attributes
        foreach (var item in validationAttributes)
        {
            if (dic.ContainsKey(Key))
                dic[Key] = string.Format("{0} {1}", dic[Key], Value);
            else
                dic.Add(Key, Value);
        }            

        // If there are any errors for a named field, we add the CSS attribute.
        ModelState modelState;
        if (helper.ViewData.ModelState.TryGetValue(fullName, out modelState) && modelState.Errors.Count > 0)
            dic.HikiAddUpdateItem("class", HtmlHelper.ValidationInputCssClassName);

        // Toggle readonly
        if (locked)
        {
            if (dic.ContainsKey("readonly"))
                dic["readonly"] = "readonly"
            else
                dic.Add("readonly", "readonly");                
        }

        // Return textbox
        return helper.TextBoxFor(expression, dic);
    }

Comments

0

try this:

@Html.TextBoxFor(model  => model.PrimaryAddressLine1, new { @id = "oid", @class= "addressfield" })
<span style="color: Red">@Html.ValidationMessageFor(model  => model.PrimaryAddressLine1)</span>

1 Comment

This just adds the validation message next to the field it wont't change the css class of the actual field. I don't want to add validation messages next to each field as it wont work in my design.

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.