简体   繁体   中英

ASP .NET MVC 3 Custom Html 5 Data- Attributes using C#

I have the following Problem.

I have Html elements that I want to affix Data- attributes and a specific class to Like so :

<element id="" class="custom_class" data-attribute="value" data-attr-two="value2"></element>

But I want To define these attributes at the model level like so :

public class ModelName 
{
  [DataAnnotation({attribute = "value", attr_2 = "value2"})]
  [Class= "custom_class"]
  public type PropertyName { get; set;}
}

I am Aware of Custom validation attributes but the problem With them is the element will look like this :

<element id="" class="custom_class" data-val-attribute="value"/></element>

And not this :

<element id="" class="custom_class" data-attribute="value"/></element>

If there is another way to do this like Perhaps adding another dictionary to Html helpers Like this :

@Html.TextBoxFor(model => Model, new { DataAnnotation : DataAnnotationObjectModel.Create({Message =        "something", Name = "something" }) )

The DataAnnotationObject would be a class with all the types of data- attributes id be using and some methods wich create default objects that are pre enumerated with repetitive data.

I Know I can do this :

@Html.TextBoxFor(model => Model, new { data_attr = @item.Value }  )

But Im going have to add 5 or more attributes and for every property in every model that I want to do it to and im going to have to do it atleast 3 times for each Property.

Is there a way to do this?

If you have some trouble Understanding this question please feel free to post a comment with your questions and I will try my best to explain

As a quick solution you could try defining an HTML Helper like this;

public static MvcHtmlString AttributedTextBoxFor<TModel, TProperty>(this HtmlHelper _helper, Expression<Func<TModel, TProperty>> expression)

In the code you should be able to retrieve the Property being referenced from the expression (follow this StackOverflow question ) and by using Reflection you should again be able to get the attributes for that property (PropertyInfo.Attributes). Once you have those, you should be able to generate an anonymous object with all the "data-" attributes defined and, from your helper defined above, return the standard TextBoxFor and pass in this object:

return _helper.TextBoxFor(expression, myHtmlAttributes);

Did not have much time to write a full solution but it should be just a few lines of boilerplate code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM