Explain Codes LogoExplain Codes Logo

Html5 data-* with asp.net mvc TextboxFor html attributes

html
data-attributes
asp-net-mvc
html5
Anton ShumikhinbyAnton Shumikhin·Nov 10, 2024
TLDR

To add data-* attributes, use an anonymous object in @Html.TextBoxFor:

@Html.TextBoxFor(model => model.Property, new { data_custom = "value" }) // In MVC, we use underscore like nobody’s business

Which gives:

<input type="text" data-custom="value" ...> // Voila! An underscore turns into hyphen, like a magic trick.

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.TextBoxFor(model => model.Username, new { data_user_id = "12345", data_sign_up_date = DateTime.Now.ToString("yyyy-MM-dd") }) // If only changing names was this easy in real life….

HTML output:

<input type="text" data-user-id="12345" data-sign-up-date="2022-01-01" ...> // Look Ma, no underscores even though they were there in C#!

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:

@Html.TextBoxFor(model => model.ReturnUrl, new { data_return_url = Url.Action("LoginSuccess", "Account") }) // Our handy little Url.Action at work

Effectively generates:

<input type="text" data-return-url="/Account/LoginSuccess" ...> // Users find their way back to the LoginSuccess action

Support for older MVC versions

In MVC versions prior to 3, Dictionary<string, object> is your savior for adding data attributes:

@Html.TextBoxFor(model => model.Property, new Dictionary<string, object> { { "data-date", DateTime.Now.ToShortDateString() } }) // Good ol’ Dictionary comes to rescue!

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 -

// Add validation like a pro with these data attributes! @Html.TextBoxFor(model => model.Age, new { data_val_required = "Age is required.", data_val_range_min = "18", data_val_range_max = "100" })

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 -

// Who needs a server when you can stash JSON right here? @Html.TextBoxFor(model => model.Property, new { data_model_json = Json.Encode(Model.MyObject) })

Beware of potential performance pitfall with huge datasets!

Cascading dropdowns with data-*

Populate cascading dropdowns using parameters fetched from data attributes -

// Isn't it fun to control cities with a dropdown? @Html.DropDownListFor(model => model.State, StateList, new { data_url = Url.Action("GetCitiesByState"), data_target = "#CityDropdown" })

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.