使用带有必需属性的 Html.LabelFor() 时显示星号

发布于 08-26 09:19 字数 290 浏览 6 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

硪扪都還晓2024-09-02 09:19:43

您应该创建自己的视图助手,而不是使用 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/.

风吹短裙飘2024-09-02 09:19:43

您需要创建自己的默认模板。 Brad Wilson 的这篇文章系列介绍了如何执行此操作:

http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html

You need to create your own default templates. This article series by Brad Wilson explains how to do this:

http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文