且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在HTML属性名称ASP.NET MVC razor视图引擎上使用自定义符号

更新时间:2023-02-25 21:28:39

记住新{property =value};是创建匿名类型的语法。因此,类型中定义的属性名称仍必须遵循标识符命名规则。所以禁止使用诸如'@',':','。'之类的符号。



在标识符之前使用@并不是逃避,但是C#语言的一个功能是允许你使用关键字作为标识符。



因此,如果你想使用高度自定义的属性名称,你唯一的选择就是传递一个IDictionary 。说到这一点,我鼓励您改为使用自定义属性的数据前缀。不仅是标准,而且HtmlHelper还有内置支持。在定义匿名类型时,只需使用下划线代替连字符,HtmlHelper将转换它们。
Remember that new { property = "value" }; is the syntax for creating an anonymous type. As such, the property names defined within the type still have to follow the identifier naming rules. So using symbols such as '@', ':', '.' is prohibited.

Using the @ before an identifier isn't so much as an escape, but a feature of the C# language that lets you use keywords as identifiers.

So if you want to use highly customized attribute names, your only option is to pass an IDictionary. With saying that, I encourage you to to instead use the data- prefix for custom attributes. Not only is that standard, but the HtmlHelper has built-in support. Simply use underscores in place of the hyphens when defining your anonymous type, and the HtmlHelper will convert them.