How to add my own HTML attribute or CSS class using the .NET data annotation attribute?

I am using ASP.NET MVC 3 RTM. Is it possible to change the HTML rendering from the View Model 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 displayed HTML, this property results. I know that this correctly cannot be done only with an attribute. I probably should connect to the system implementing the interface, but where should I look?

I know that MVC uses the default editor templates, and I looked at them in the source code of MVC 3, but I was not able to figure out if I could somehow connect to the rendered element and add some attributes. I know the validation system does this by adding custom HTML attributes to support unobtrusive validation.

I think I need a pointer to where I should look, or what interface I should look at.

Thank you very much.

Update: I use the standard HTML helper Html.EditorFor(model => model.Name) for my fields and do not override any editor templates. I would prefer it if I didn't have to change or override the default templates.

+4
source share
1 answer

You can check out the following blog post that illustrates how to achieve this by writing your own DataAnnotationsModelMetadataProvider attribute and overriding the default templates.

+5
source

All Articles