Html.ValidationMessageFor Text Color

2020-08-11 11:04发布

问题:

Probably a simple question, but i cant seem to find the answer.

using MVC 2 i have a series of Html.ValidationFor controls. I want to assign a CSS class to the text and cant seem to do it.

<%= Html.TextBoxFor(Model => Model.Chest, new { @class = "textBoxMeasure" })%>
<%= Html.ValidationMessageFor(Model => Model.Chest) %>

if i try the same method as textboxfor i get errors because it requires a string, when i put a string in it still wont work!

thanks

回答1:

There's a variant that takes htmlAttributes as the third argument (the second is the message that should be displayed, or you can use null for the default validation message)

Html.ValidationMessageFor(
        Model => Model.Chest, 
        "Please enter a value", 
        new { @class = "redText" })

For more info see http://msdn.microsoft.com/en-us/library/ee721293%28v=vs.98%29.aspx



回答2:

I added a comment to the accepted answer, but I cannot to format it for better view. So, here is my already formatted comment from the accepted response.

I had similar case and I used solution from accepted answer. But I desired to use message from model annotation. I tried this:

@Html.ValidationMessageFor(Model => Model.Chest, null, new { @class = "text-danger" });

and it correctly worked for me. I used MVC4 with bootstrap.



回答3:

Use the classes assigned to the span tag holding the message. If the field is valid the class is field-validation-valid. If there is an error its field-validation-error.

I use

    .field-validation-error {
        color:Red;
    }


回答4:

simplest way to do this to put @Html.ValidationMessageFor in div tag and apply css to div tag

    <div style="font-size:15px !important;">
             @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
    </div>