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

标签 c# asp.net-mvc asp.net-mvc-4 knockout.js html

大多数在 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

关于c# - 为 htmlAttributes 提供值,其中键在 MVC View 中的名称中包含破折号(例如 "data-bind"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18851282/

相关文章:

c# - 在部分 View 中显示用户角色

c# - ASP.NET - 发生异常时发送电子邮件

asp.net - NHibernate - 访问同一个数据库的两个 SessionFactories

c# - 你如何获得一天中的当前时间?

c# - 连接状态关闭时如何发生 Ora-24309?

c# - 在mvc中清除浏览器缓存中的对象

asp.net - 如何在不使用系统 css 但具有自己样式的 asp.net mvc 应用程序中包含静态 html?

c# - 当用户按下 Enter/Return 键时调用服务器端操作

c# - 想从类中调用 Controller 方法并在不向 Controller 发出请求的情况下获取 Controller 上下文?

JQuery 提交在 Chrome 中不起作用