16

I have defined a custom html attribute "data-something-something". In my view I use an Html extension method to create for instance a text box. One of the parameters is an anonymous object HtmlAttributes. I want to pass this value: new { data-something-something = "value" }. However, data-something-something is not recognized by .NET as a property name because of the hyphens.

I changed it to dataSomethingSomething for now, but I would like to define my custom attribute according to the HTML 5 standard (i.e. prefix it with 'data-').

I had a similar problem before when trying to do new { class = "class-name"} on the class property. For this case I found that I can prefix class with an '@' symbol to make it work (i.e. new { @class = "class-name"}). Because there is a solution for this scenario, I hoped that there might be a solution for my current problem (prefixing it with an '@' did not work).

Thanks in advance.

1 Answer 1

29

Try using underscores which should be automatically converted into dashes by the standard HTML helpers:

new { data_something_something = "value" }
Sign up to request clarification or add additional context in comments.

3 Comments

Neato! I was hoping for something like this.
@Matthijs Wessels, are you using a custom HTML helper? If yes, please show your helper code and usage. This definitely works with the built-in helpers. Try it: @Html.TextBoxFor(x => x.Foo, new { data_something_something = "value" }).
I only use built-in helpers. Already tried it and it worked :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.