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

1

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

Soberminded answered 25/2, 2012 at 14:23 Comment(0)
G
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.

Griselgriselda answered 25/2, 2012 at 14:25 Comment(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?Ledbetter
Just transform this: new { data_test="true"}) -> new Dictionary<string, object> { { "data-test", "true" } });Rehabilitate
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. :)Starr
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.Roughspoken

© 2022 - 2024 — McMap. All rights reserved.