为 htmlAttributes 提供值,其中键在 MVC 视图中的名称中包含破折号(例如“data-bind”)

本文关键字:破折号 包含 例如 data-bind 视图 htmlAttributes MVC | 更新日期: 2023-09-27 18:31:41

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

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

例如,让我们以以下示例为例:

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

在您的视图中尝试上述代码,在运行时它会显示错误屏幕并显示以下消息:

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提供具有破折号字符的属性键;如"data-bind"?

为 htmlAttributes 提供值,其中键在 MVC 视图中的名称中包含破折号(例如“data-bind”)

在媒体资源名称中,将所有短划线-字符替换为下划线_(如下例所示):

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

这将起作用,因为所有 HTML 帮助程序在渲染 HTML 时都将属性名称中的下划线_转换为破折号-;即,例如,data_bind在 html 中输出时转换为 data-bind

这并不总是正确的。 假设您在网址中使用参数。

@Html.ActionLink("Add Job", "Index", "Home", new { foo_bar = "foobar" }, new { @class = "btn btn-default", data_foo = "bar" })

data_foo确实呈现为"data-foo",但参数仍保留为下栏。您的结果将是 :http://your.domain/yourapp/?foo_bar=foobar

当然,您实际上不能使用破折号,否则会出现OP中指定的错误。

我已经解决了这个问题,如下所示,但我有兴趣看看将来是否有人会有更好的方法:

@{
   var link = Html.ActionLink("Add Job", "Index", "Home", new { foo_bar = "foobar" }, new { @class = "btn btn-default", data_foo = "bar" });
}
@Html.Raw(link.ToString().Replace('_', '-'))

使用 HtmlHelper.AnonymousObjectToHtmlAttributes 方法。以下代码将向文本输入框添加工具提示,工具提示显示模型上 MyIntVal 的 DisplayAttribute 说明中的数据。

@{
    var htmlAttributesWithDashes =  HtmlHelper.AnonymousObjectToHtmlAttributes(
        new
        {
            id = "myTextBoxId",
            data_toggle = "tooltip",
            data_position = "left top",
            title = ModelMetadata.FromLambdaExpression( m => m.MyIntVal, ViewData ).Description
        }
        );

}
<div class="col-sm-6">
    @Html.TextBoxFor( m => m.MyIntVal, htmlAttributesWithDashes )
</div>