使用带有必需属性的 Html.LabelFor() 时显示星号
我正在使用 ASP.NET MVC2 和数据注释。
我已经用必需属性装饰了我的好友类中的一个属性。
有没有办法让 Html.LabelFor() 辅助方法自动显示星号来表示该字段是必填的?
我能想到的唯一方法是:
a) 扩展 LabelExtensions
或
b) 手动将星号添加到 DisplayName 属性,例如“My Field *”
后者最简单,但引入了 DisplayName 和必需属性之间的依赖关系。
还有其他建议吗?
I'm using ASP.NET MVC2 and Data Annotations.
I've decorated a property in my buddy class with the Required attribute.
Is there a way to get the Html.LabelFor() helper method to automatically display an asterix to signify that the field is required?
Only ways I can think of to do this are:
a) Extend LabelExtensions
Or
b) Manually add the asterix to the DisplayName attribute, e.g. "My Field *"
The latter is simplest, but introduces a dependency between the DisplayName and Required attributes.
Any other suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您应该创建自己的视图助手,而不是使用
Html.LabelFor
,它将创建标签并插入适当的*
。您可以在 找到有关如何创建新视图助手的详细信息(这非常简单) http://mvcviewhelpers.codeplex.com/。Instead of using the
Html.LabelFor
, you should create your own view helper which will create the label and insert the*
is appropriate. You can find detailed info about how to create a new view helper (which is very easy) at http://mvcviewhelpers.codeplex.com/.