I’m looking to create an unobtrusive cascading dropdown system for a website I’m working on. I’m having trouble figuring out how to get the various HtmlHelper methods to include the custom html attributes to the rendered tag, though.
Looking through the source for the built in HtmlHelper methods, they all make a call to GetUnobtrusiveValidationAttributes, which creates all the data-val-* html attributes . That’s great if you need the validator attributes, but I’d like to be able to add other attributes this way without needing to alter templates and create new HtmlHelper extensions.
Is this at all possible? Am I overlooking something?
Edit
I know that all the HtmlHelper methods have an overload that accepts an object with html attributes. I’m trying to avoid this if at all possible.
Edit 2
I essentially want this to happen:
public class ViewModel
{
[Cascading(Action="/Controller/Action")]
public int Action { get; set; }
}
And then have the HtmlHelpers render out like:
<select data-action="/Controller/Action"></select>
But preferrably without having to write up an extension method to do it. I have no problem making my own helper method to do it, but I’m wondering if I’m missing some built in feature that already looks at random model metadata and can add html attributes.
Seeing edit 1+2, I think you need to create your own extensions. Since you are dealing with dropdowns, you can have a look at this implementation but use custom attributes via
IMetadataAware.This part is no longer useful as an answer
If you want to add custom attributes to the generated HTML, you can use the
Object htmlAttributesparameter available on many helpers, for example in@Html.ActionLink().Example with custom
data-*attributes that might be used to unobtrusively initiate a modal dialog for editing user settings on javascript enabled clients. Bootstrap’s modal uses something similar to this.Note that I’m using underscores instead of dashes for the data attribute.
In your case, I guess you are using
@Html.DropDownList(...), which takeshtmlAttributesas well. Populate them as you like and let your javascript pick up the rightdata-*attributes.