Search code examples
c#razor-2

C# HtmlHelpers How to Escape / Preserve underscores in attribute names


when using HtmlHelpers in Razor code, like this:

new { data-something_something = "value" }

The underscores are converted "magically" to hyphens. But what if I need my attributes to contain underscores AND hyphens? How can I escape or otherwise preserve the underscore?


Solution

  • You can pass an IDictinoary<string, string> instead:

    @Html.TextBoxFor(x => x.Prop, new Dictionary<string, string> { { "data-something_something", "value" } })
    

    Please note that attribute names like some_attr is considered invalid HTML, but in your case data-* attributes can indeed contain underscores.

    See MSDN