Skip to main content
 首页 » 编程设计

c#之为 htmlAttributes 提供值,其中键在 MVC View 中的名称中包含破折号(例如 "data-bind")

2024年02月13日20pander-it

大多数在 ASP.Net MVC 中可用的 Html 帮助程序都带有 object htmlAttributes 重载。这用于为输出的标签提供额外的属性值。在使用匿名对象表示法指定 htmlAttributes 值时,它们的属性名称必须是有效的 c# 标识符。

现在,当您尝试输出带有破折号 - 字符的属性时,问题就出现了(例如,knockout js 的“data-bind”属性)

举个例子:

@Html.TextBox("Title", string.Empty, new { data-bind="text: title" }) 

在您的 View 中尝试上面的代码,在运行时它会显示带有以下消息的错误屏幕:

Compilation Error 
 
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 
 
Compiler Error Message: CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access. 

所以问题是,如何为 htmlAttributes 提供带有破折号的属性键;像“数据绑定(bind)”?

请您参考如下方法:

在您的属性名称中,将所有破折号 - 字符替换为下划线 _(如下例所示):

@Html.TextBox("Title", string.Empty, new { data_bind="text: title" }) 

这是可行的,因为所有 HTML 助手在呈现 HTML 时都会将属性名称中的下划线 _ 转换为破折号 -;即对于您的示例,data_bind 在以 html 格式输出时会转换为 data-bind。