1

If I add [RequiredIf(... to a property I have on a view model class, MVC adds certain data-required... attributes to the resulting mark-up for that property.

I want to do the same; I want to decorate a property of my view model class with [MyMarkup] and have it render data-my-attribute on the rendered HTML for that property's editor.

I have looked high and low for a solution, and haven't found one, which leads me to suspect my approach may be wrong.

What I've Tried

I've tried extending Attribute but can't see how I'd access mark-up in there, since attributes wouldn't generally be concerned with mark-up.

I also looked into data annotations and metadata-aware implementations too, but can't find anything that would allow me to add a data attribute to an element.

Is this possible at all?

Please Note

I'm aware of HTML helpers and that I can pass in custom attributes to them, but I want to keep this as an attribute.

  • You can create a class that implements `IMetadataAware` and add a value to `ModelMetadata.AdditionalProperties` and then create you own `HtmlHelper` extension method to generate the html. But if this is related to your last (nor deleted) question then I think your on the wrong track. –  Feb 08 '16 at 11:12
  • @StephenMuecke - it is. In summary, I want to be able to decorate my property with this `DisplayIfRequired` attribute and it add `data-display-if-required` to my HTML element. I could pass this in to the helper and be done with it, but I'd prefer to keep all this in one place, as the data annotations are. Again, much appreciated, thanks for your reply. –  Feb 08 '16 at 11:14
  • Refer [this answer](http://stackoverflow.com/questions/26519493/customattribute-reflects-html-attribute-mvc5/26519946#26519946) for an example of the approach I mentioned above –  Feb 08 '16 at 11:15
  • @StephenMuecke thanks a lot. So we can say that what I'm attempting to do isn't possible with an attribute alone? I must have a HTML helper to pick up on the new metadata I'm defining? –  Feb 08 '16 at 11:17
  • Not with an attribute alone. And using the above approach will only handle the initial rendered visibility based on the 'other property value' (as weel as adding the attribute). In addition you still going to have to use javascript/jquery to handling client side changes. –  Feb 08 '16 at 11:20
  • @StephenMuecke I'm with having to cater for this in javascript since the js validator is all custom anyway (don't ask), so needs extending. But it would be ideal to define this data attribute in the same place I'd defined all of the others. Never mind. –  Feb 08 '16 at 11:22

0 Answers0