This article is a mirror article of machine translation, please click here to jump to the original article.

View: 19195|Reply: 0

[ASP.NET] Use Razor to generate data-attributes in HTML5

[Copy link]
Posted on 3/19/2019 1:04:48 PM | | |
In HTML5, you can use the data- attribute to represent user data, which can even be data in JSON format, which is very convenient for web front-end development.

In MVC's Razor, you can use anonymous objects to generate custom attributes, but they can't pass Razor's syntax checks.

The compiler reports the error directly.  The name 'data' does not exist in the current context for the simple reason that the - sign is used as an operator.
In fact, the method provided by HtmlHelper, AnonymousObjectToHtmlAttributes, can solve this problem, and the description of the method is shown below.

Replaces underscore characters (_) with hyphens (-) in the specified HTML attributes.
We can use the underscore (_) directly in the anonymous object instead of the minus sign (-), and HtmlHelper will replace the underscore with the minus sign in the rendering.

For example, the following writing

The following HTML5 markup is generated.







Previous:SSH to the client
Next:C# Enum enum type operation extension class
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com