How to use dashes in HTML-5 data-* attributes in ASP.NET MVC
In ASP.NET MVC, replace dashes with underscores in data-*
attributes in your C# model to ensure compatibility:
C# Model:
Razor View:
Renders as:
When you have underscores in C#, Razor converts them back to their "dashing" counterparts in HTML.
Translating attribute names: underscores to dashes
ASP.NET MVC 1 does not allow dashes in attribute names, instead preferring underscores. We can use a workaround by creating a static method or a custom HTML helper to replace underscores with dashes.
Quenching Razor's thirst for dashes
ASP.NET MVC will automatically replace underscores with dashes
When rendering controls, use this method to put the dash back to where it belongs:
Convince Razor to accept dashes - Create a custom helper
A custom HTML helper is the diplomat who can resolve the "_ vs -" conflict for us:
Make use of this peacekeeper in the view:
Bridge the JavaScript barrier using data attributes
HTML5 data attributes act as the translator between your front-end and back-end. Ensure these translators are effective by using underscores in ASP.NET MVC that get converted back to dashes in HTML for JavaScript to understand.
Talking directly to data attributes in JavaScript
The dataset
property in JavaScript is our secret decoder ring 🕵️♂️ to access the data-*
attributes:
Playing it clean with the DisplayName attribute
ENSURE readable and clean code by adding nicknames to your model properties.
Let Razor take care of the rest:
Holding the line with older ASP.NET versions
When locked into older frameworks of ASP.NET, think out of the box with workaround solutions.
Class attributes: A fallback option?
Consider using class for passing custom data:
Extract the value on the front-end like a valued treasure, when passing data items is crucial but constraint.
Was this article helpful?