开发者

@Html.ValidationMessageFor() custom validationMessage always shown

开发者 https://www.devze.com 2023-03-12 05:44 出处:网络
I am trying to use a different message for @Html.ValidationMessageFor() in ASP.NET MVC3. This works fine but it seems to make the message be always displayed , e.g. if I do this:

I am trying to use a different message for @Html.ValidationMessageFor() in ASP.NET MVC3. This works fine but it seems to make the message be always displayed , e.g. if I do this:

@Html.ValidationMessageFor(model => model.TimesheetEntry.Product)

then the error is only shown when I submit the form and it is invalid. However if I do this:

@Html.ValidationMessageFor(model => model.TimesheetEntry.Product, "custom error")

then that message 开发者_C百科is displayed as soon as I initially load the page. I'm probably doing something stupid here and any help would be appreciated.


Have you tried the CSS from this question?

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


probably you have model parameter in your httpGet ActionResult method


I also had this problem and did the "hack" from above by adding the two css-classes with display none. I then discovered that if I moved my error-message to my model and used empty string as parameter in ValidationMessageFor everything solved out and I was able to delete the two classes.

In model

 [Display(Name = "Caption"), Required(ErrorMessage = "Caption is required")]

In cshtml

@Html.EditorFor(m => m.caption, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.caption, "", new { @class = "text-danger" })


I have not played with validation enough in MVC 3, so I am just running through the way I would troubleshoot this issue.

I would look at this: http://msdn.microsoft.com/en-us/library/dd470929.aspx

Yeah, standard MSDN documentation, but the ValidationMessageFor() method states:

Returns the HTML markup for a validation-error message for each data field that is represented by the specified expression, using the specified message.

That sounds, to me, like it should always return the message, even when you are not supplying a custom message as a string. It looks like there are other methods that may better fit your need on the URI specified.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号