How to specify data attributes in razor, e.g., data-externalid="23151" on @this.Html.CheckBoxFor(...)


C# Problem Overview

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

With razor, I'm unable to specify values for data- attributes such as data-externalid="23521"

Is there a way to do this using @this.Html.CheckBoxFor(...)?

C# Solutions

Solution 1 - C#

    m => m.MyModel.MyBoolProperty, 
    new { 
        @class = "myCheckBox", 
        data_externalid = "23521"

The _ will automatically be converted to - in the resulting markup:

<input type="checkbox" name="MyModel.MyBoolProperty" data-externalid="23521" class="myCheckBox" />

And that's true for all Html helpers taking a htmlAttributes anonymous object as argument, not only the CheckBoxFor helper.


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIan DavisView Question on Stackoverflow
Solution 1 - C#Darin DimitrovView Answer on Stackoverflow