128
@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(...)?

Ian Davis
  • 19,091
  • 30
  • 85
  • 133

1 Answers1

286
@Html.CheckBoxFor(
    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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 4
    wow, I can see the '_' '-' conversion being really confusing... especially if someone does a string search looking for a given data attribute. Is there another way? – RayLoveless Oct 08 '14 at 17:50
  • 5
    Just transform this: new { data_test="true"}) -> new Dictionary { { "data-test", "true" } }); – Dominique Alexandre Apr 23 '15 at 14:47
  • 1
    And if you need the value to come from your ViewModel; `new { @class = "myCheckBox", data_externalid = Model.ExternalId }` I came looking for help on this topic and this was what I needed. :) – Scott Fraley Jan 26 '17 at 19:04
  • Over 8 years later this answer has just helped me out massively. I couldn't work out why adding my vue form v-model tag wouldn't work. I had to use v_model="blah" instead. – Andrew Howard May 01 '20 at 15:15