ASP.NET MVC 2 客户端验证不适用于 Html.ValidationMessage()?
我试图获得一个非常简单的客户端验证示例,以便在 ASP.NET MVC 2 中工作。我使用数据注释来设置所需的属性“姓氏”。当我使用 Html.ValidationMessageFor(x => x.Surname) 时,正确的客户端验证脚本将写入页面。但是,当我使用 Html.ValidationMessage("Surname") 时,客户端验证直到页面发布后才会呈现。客户端验证仅在表单发布后开始工作!我可以看到脚本在表单发布后在页面中更新。 Html.ValidationMessage() 中似乎存在错误?
I'm trying to get a very simple client side validation example to work in ASP.NET MVC 2. I'm using data annotations to set a required property "Surname". When I use the Html.ValidationMessageFor(x => x.Surname) the correct client side validation script is written to the page. But when I use Html.ValidationMessage("Surname") the client side validation is not rendered out until after the page has been posted. Client side validation only starts working after a form post! I can see that the script is updated in the page after a form post. There appears to be a bug in Html.ValidationMessage()?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
确保您在母版页标题中引用了正确的脚本。
还要查看您的视图,以确保客户端验证调用位于您的表单之上
,当然还有您的验证消息以显示问题。
这确实是您所需要的。我相信,如果您在字段中输入文本,然后从字段中删除文本和制表符,则 required 属性只会开始检查,因此请尝试看看是否获得验证。其他人将在需要时验证该属性。例如,当超过 50 个字符时,
[StringLength(50)]
将显示错误消息。Make sure you are referencing the correct scripts in your master page head.
also look at your view to make sure the client validation call is above your form
and of course your validation message to show the problem.
That is really all you need. I believe the required attribute will only start its check if you enter text in the field then remove the text and tab out of the field, so try that to see if you get the validation. Others will validate when the attribute needs to. For example the
[StringLength(50)]
will show an error message when you exceed 50 characters.我没有尝试过,但元数据存储在属性上,因此只有 ValidationMessageFor 能够检查属性(通过静态反射)。
另一个助手使用字符串键来访问模型状态字典,而不引用任何属性(并且没有验证元数据信息),因此我不认为 Html.ValidationMessage(string key) 能够在客户端注入验证脚本。
i've not tried but the metadata are stored on the proprerty so only the ValidationMessageFor has the ability to check the prop (via static reflection).
The other helper use a string key to access a modelstate dictionary without any reference to the property (and no validation metadata info), so i dot't think the Html.ValidationMessage(string key) has the ability to inject validation script client-side.
据我所知,即使是在客户端,验证也需要尝试进行验证。
您可以尝试在 GET 视图上创建模型的新实例,然后在将其发送到视图之前使用 TryValidateModel() 。这应该会导致验证逻辑运行,从而填充客户端验证,这将导致所有必填字段显示其错误版本,但根据您选择的样式设置,这不一定是一个大问题。
As far as I know the validation requires an attempt to validate even if it's client side.
You could try on the GET view creating a new instance of your model, then use TryValidateModel() before sending it to the view. This should cause the validation logic to run and thus to populate the clientside validation, this will result in all required fields showing their error version but depending how you choose to style them this doesn't have to be a big issue.