LiamHT
LiamHT

Reputation: 1332

Custom Attribute in c# to give Custom data-attribute in html

I'd like to be able to make a data attribute in c# for an object in my model. When this is displayed. I'd like the html to render the value in a data attribute within the html itself.

In my head, the code looks similar to this.

public class AffectsAttribute:Attribute
{
    public string[] Departments { get; set; }

}


[EmailAddress]
[Required(ErrorMessage = "Email is required")]
[Affects(Departments = new string[]{"Coaches"})]
public string Email {get; set;}

Then in the html, after being called with razor it would look something like this

@Html.EditorFor(model => model.Email)


<input class="text-box single-line" data-affects="Coaches" data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="Email is required" id="Email" name="Email" type="email"  value="">

I have no clue how to specify that I would like the additional data attribute to be added when the item is rendered on a page. Can anyone help?

Upvotes: 1

Views: 1531

Answers (2)

brduca
brduca

Reputation: 3623

You'll have to create a new HTML helper to do that. http://www.asp.net/mvc/overview/older-versions-1/views/creating-custom-html-helpers-cs

It's an extension from the HtmlHelper, that creates that. Something like:

  public static class YourExtensions
 {
      public static string YourMethodName(this HtmlHelper helper, string[] paramName)
      {
           return  String.Format("<input data-affects='{0}'>",String.Join(" ", paramName));
      }
 }

Upvotes: 0

beautifulcoder
beautifulcoder

Reputation: 11320

It can be done through the ValidationAttribute. If you inherit this:

public class MyCustomAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
    }
}

The GetClientValidationRules is what you are interested in. You return an IEnumerable of attributes you want the client to have.

You can check out this article on CodeProject.

Upvotes: 1

Related Questions