Injecting Custom HTML Attributes in ASP.NET MVC
Recently Stuart Leeks and I have developed a worrying pattern of having the same ideas at the same time. I’m starting to doubt we’re different people. Except he’s about a foot taller so maybe that’s aspirational from my side.
Our latest coinciding of ideas was a way to automatically inject HTML attributes for fields rendered as part of your model with Html.EditorFor. We’ve just blogged about it on our team blog – Adding Html Attributes in Templated Helpers, published the code on the MSDN Code Gallery under UkadcHtmlAttributeProvider, and pushed a working version to NuGet under UkadcHtmlAttributeProvider.
Have a read of the blog post to learn more. To try our solution just use the NuGet command;
Install-Package UkadcHtmlAttributeProvider
A few examples of attribute provider delegate registrations are below. Do let us know if you like the approach!
Output the aria-required attribute for required fields;
HtmlAttributeProvider.Register(
metadata => metadata.IsRequired,
"aria-required",
"true");
This results in the following HTML for a string field;
<input aria-required="true" class="text-box single-line" … snip … />
Output an HTML 5 Custom Data Attribute (CDA) when the field contains a URL;
HtmlAttributeProvider.Register(
metadata => metadata.DataTypeName == "Url",
"data-url",
"true");
This results in the following HTML for a string field;
<input class="text-box single-line" data-url="true" … snip … />
Output the Square Root of a value of a number field as an HTML 5 CDA;
HtmlAttributeProvider.Register((html, metadata) =>
{
if (metadata.ModelType == typeof(Int32))
return new[]
{
new KeyValuePair<string, object>(
"data-sqroot-value",
Math.Sqrt(
Convert.ToDouble(metadata.Model)))
};
return Enumerable.Empty<KeyValuePair<string, object>>();
});
This results in the following HTML for an Integer field;
<input class="text-box single-line" data-sqroot-value="4.58257569495584" … snip… />
OK so that last one is a bit arbitrary – but there’s a huge amount you can do here. Think of tab indexes, URLs for Ajax callbacks, CSS classes… the list goes on.
Head over to the blog post to read about how it works. And check out Stu’s follow-up post on some good real examples.
Original Post by Simon Ince on May 24th, 2012