如何在剃刀中指定数据属性,例如@ this.Html.CheckBoxFor(...)上的data-externalid ="23151"

Ian*_*vis 115 .net c# razor

@this.Html.CheckBoxFor(m => m.MyModel.MyBoolProperty, new { @class="myCheckBox", extraAttr="23521"})
Run Code Online (Sandbox Code Playgroud)

使用razor,我无法指定数据属性的值,例如 data-externalid="23521"

有没有办法使用@this.Html.CheckBoxFor(...)

Dar*_*rov 248

@Html.CheckBoxFor(
    m => m.MyModel.MyBoolProperty, 
    new { 
        @class = "myCheckBox", 
        data_externalid = "23521"
    }
)
Run Code Online (Sandbox Code Playgroud)

_将自动转换到-在所得的标记:

<input type="checkbox" name="MyModel.MyBoolProperty" data-externalid="23521" class="myCheckBox" />
Run Code Online (Sandbox Code Playgroud)

对于所有使用htmlAttributes匿名对象作为参数的Html助手而言,这都是正确的,而不仅仅是CheckBoxFor助手.

  • 只需转换它:new {data_test ="true"}) - > new Dictionary <string,object> {{"data-test","true"}}); (5认同)
  • 哇,我可以看到'_'' - '转换真的令人困惑...特别是如果有人进行字符串搜索寻找给定的数据属性.还有另外一种方法吗? (4认同)