如何使用 .NET 数据注释属性附加自定义 HTML 属性或 CSS 类?
我正在使用 ASP.NET MVC 3 RTM。是否可以使用属性来更改从视图模型呈现的 HTML?
示例:
public class Product
{
[AddHtmlAttribute(Name = "disabled", Value = "disabled")]
public string Name { get; set; }
}
我希望该属性能够更改呈现的 HTML,该属性导致。我知道单独使用属性无法正确完成此操作。我可能必须通过实现接口来连接系统,但是我应该在哪里寻找?
我知道 MVC 使用默认的编辑器模板,并且我在 MVC 3 源代码中查看了它们,但我无法弄清楚是否可以以某种方式挂钩到渲染的元素并添加一些属性。我知道验证系统通过添加自定义 HTML 属性来支持不显眼的验证来实现此目的。
我想我只需要一个指向我应该查看的位置,或者我应该查看哪个界面的指针。
太感谢了。
更新:我正在为我的字段使用标准 HTML 帮助器 Html.EditorFor(model => model.Name)
,并且没有覆盖任何编辑器模板。如果我不必更改或覆盖默认模板,我真的会更喜欢。
I'm using ASP.NET MVC 3 RTM. Is it possible to change the HTML rendered from a View Model, by using an attribute?
Example:
public class Product
{
[AddHtmlAttribute(Name = "disabled", Value = "disabled")]
public string Name { get; set; }
}
I want the attribute to be able to change the rendered HTML, that property results in. I know it properly can't be done with an attribute alone. I probably have to hook into the system by implementing an interface, but where should I look?
I know MVC uses the default editor templates, and I've looked at them in the MVC 3 source code, but I haven't been able to figure out if it would be possible to somehow hook into the rendered element and add some attributes. I know the validation system does this, by adding custom HTML attributes to support unobtrusive validation.
I guess I just need a pointer to where I should look, or what interface I should take a look at.
Thank you so much.
Update: I'm using the standard HTML helper Html.EditorFor(model => model.Name)
for my fields, and haven't overriden any editor templates. I would really prefer if I didn't have to change or override the default templates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以查看 以下博客文章说明了如何通过编写自定义代码来实现此目的
DataAnnotationsModelMetadataProvider
,属性并覆盖默认模板。You may checkout the following blog post which illustrates how to achieve this by writing a custom
DataAnnotationsModelMetadataProvider
, attribute and overriding the default templates.