ASP.NET MVC ModelMetaData:有没有办法根据RequiredAttribute设置IsRequired?
Brad Wilson 发布了有关 ASP.NET MVC 新 ModelMetaData 的精彩博客系列: http://bradwilson.typepad .com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html
在其中,他描述了 ModelMetaData 类现在如何在视图和模板化帮助器中公开。我想要做的是,如果字段是必需的,则在表单字段标签旁边显示一个星号,因此我考虑使用 ModelMetaData 的 IsRequired 属性。但是,默认情况下,IsRequired 对于所有不可为 null 的属性为 true,而对于所有可为 null 的属性为 false。问题是,字符串始终可为 null,因此 IsRequired 属性对于字符串始终为 false。有谁知道如何覆盖 IsRequired 设置的默认值?或者,我考虑利用我用来装饰我的属性的RequiredAttribute 属性,但RequiredAttribute 似乎没有通过ModelMetaData 类公开。有谁知道如何解决这个问题?
提前致谢。
Brad Wilson posted a great blog series on ASP.NET MVC's new ModelMetaData:
http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html
In it, he describes how the ModelMetaData class is now exposed in the Views and templated helpers. What I'd like to do is display an asterisk beside a form field label if the field is required, so I thought about using the IsRequired property of ModelMetaData. However, IsRequired by default is true for all non-nullable properties, while it's false for all nullable properties. The problem is, strings are always nullable, so the IsRequired property is always false for strings. Does anyone know how to override the default of how IsRequired is set? Alternatively, I thought about leveraging the RequiredAttribute attribute that I've been decorating my properties with, but the RequiredAttribute doesn't seem to be exposed through the ModelMetaData class. Does anyone know how to get around this problem?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要创建自己的 ModelMetadataProvider。下面是使用 DataAnnotationsModelBinder 的示例
然后在 Global.asax 的 AppStartup 中,您将需要添加以下内容以连接 MyMetadataProvider 作为默认元数据提供程序:
You need to create your own ModelMetadataProvider. Here's an example using the DataAnnotationsModelBinder
Then in your AppStartup in Global.asax, you will want to put the following in to hookup the MyMetadataProvider as the default metadata provider: