ASP.NET MVC 必填字段指示符
对于我的 ASP.NET MVC 视图中已按要求归属的字段,框架是否有任何方法可以自动呈现某种指示符,表明该字段在元数据中被标记为必需?
For fields in my ASP.NET MVC view that have been attributed as required, is there any way for the framework to render some sort of indicator automatically that the field is marked as required in metadata?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
应该能够使用 CSS 来做到这一点,因为 MVC3 将这些自定义属性添加到元素中:
您可以在 CSS 中关闭 data-val-required,如下所示:
input[data-val-required] {
背景:红色
}
或设置星号等的背景图像。
Should be able to do this with CSS since MVC3 adds in those custom attributes to the element:
You could key off the data-val-required in CSS like so:
input[data-val-required] {
background:red
}
or set a background image of an asterisk etc.
我这样做是因为我的必填字段必须是动态的(在配置文件中定义)
在视图末尾添加:
I did that way because my required fields must be dynamic (defined in a configuration file)
Add at the end of your View:
我修改了 Renato Saito 的答案以包含更多字段类型(所有类型的输入和选择列表)并使用 jQuery 命名空间而不是通用的 $。这是我的修改:
I modified Renato Saito's answer to include more field types (all types of input and select lists) and use the jQuery namespace instead of the generic $. Here is my revision:
这是一个将在具有“data-val-required”属性的任何内容的右侧附加一个红色星号的示例。
Here is one that will attach a red asterisk to the right side of anything with the attribute 'data-val-required'.
添加 html 属性是不够的。这只会导致 javascript 验证错误。如果您想指示该字段是必填字段,您可能需要为其添加一个星号。您可以通过 HtmlHelper 的扩展方法来完成。您可以在这里找到完整的解释
指示 MVC 应用程序中的必填字段
Adding html attribute is not enough. This will only cause javascript validation error. If you want to indicate that the field is required you'd probaly want to add an asterisk to it. You can do it by means of extenssion method of HtmlHelper. You can find a thorough explanation here
Indicating required field in MVC application
我这边做了一个小修改。
实际上我有主键(数据库中的身份列)。我不想强调这一点。
因此,我使用下面的代码片段仅选择注释中具有必需属性的
input[type=text]
字段。A Small Modification Is Done From My Side.
Actually I had primary keys (Identity Columns in DB). That I did no want to highlight.
So I Used Below Code Snippet to select only
input[type=text]
fields that has required attribute in annotation.