Asp.net MVC 3 RC - Razor ValidationMessageFor Cust

2019-03-23 00:59发布

问题:

ASP.Net MVC 3 RC, Razor

Experiencing some unexpected behavior when I try to use a custom message and using client side validation. The problem is it always displays the custom message even though there is no error.

So say I have a Client Model where the FirstName is set as Required. If I have the following code the validation message is not displayed until I click on Submit which works as expected.

@Html.EditorFor(model => model.Client.FirstName) @Html.ValidationMessageFor(model => model.Client.FirstName)

But now say I want to customize the validation message to use an asterisk like so:

@Html.EditorFor(model => model.Client.FirstName) @Html.ValidationMessageFor(model => model.Client.FirstName, "*")

Now even before I click on the submit button, there is always an asterisk next to the field.

The expected behavior is that it would show the asterisk when there is a validation error.

Thanks for any help.

回答1:

I found the problem, the following CSS is needed:

.field-validation-valid
{
    display: none;
}
.validation-summary-valid
{
    display: none;
}

Somewhere along my refactoring those classes got taken out. They are in there by default when you start a new MVC 3 project. Hope that helps someone in the future!



回答2:

The chosen answer didn't work for me. I had to use the following. Note the class is "error", not "valid". This hides the validation message being shown on page load.

<style>
.field-validation-error
{
    display: none;
}
.validation-summary-valid
{
    display: none;
}

</style>