Problem setting an html attribute containing hyphe

2019-06-15 00:03发布

问题:

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:

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

new { data_something_something = "value" }


回答2:

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC <-- You will find your answer here