Html5 data-* with asp.net mvc TextboxFor html attributes
To add data-*
attributes, use an anonymous object in @Html.TextBoxFor
:
Which gives:
For attributes that are C# keywords, prepend @
: @data_date
for data-date
.
Translating underscores to hyphens
In ASP.NET MVC, you can seamlessly bridge your C# code with HTML5 data-*
attributes. Any underscore gets converted into hyphen, abiding by the standards for data attribute names:
HTML output:
Dynamic URLs within data attributes
Use Url.Action
for giving dynamic values to your data-*
attributes. This technique comes in handy when generating callback URLs or defining AJAX endpoints:
Effectively generates:
Support for older MVC versions
In MVC versions prior to 3, Dictionary<string, object>
is your savior for adding data attributes:
Although a tad verbose, this method gives you complete control over rendering of HTML attributes.
Power of validation with data-*
Custom data-*
attributes can act as catalysts for client-side validation -
Employ jQuery validation plugins for superior form validation experience without the need for additional server-hit.
Taming JSON in data-*
You can serialize JSON objects for utilization by JavaScript at a later stage -
Beware of potential performance pitfall with huge datasets!
Cascading dropdowns with data-*
Populate cascading dropdowns using parameters fetched from data attributes -
Leverage AJAX calls for the selected state and populate City dropdown.
Essential tips and tricks
Performance is key
Be mindful of your page size. Limit data-*
attributes to only essential data.
HTML encoding
Encode any dynamic content within data-*
attributes to prevent XSS attacks!
Stick to conventions
Adhere to a consistent naming pattern across your application. It greatly aids in maintainability and readability.
Was this article helpful?