I am trying to add a “name” attribute to my CheckBoxFor and can’t get it to work.
@Html.CheckBoxFor(
model => model.ProvidePracticalSuggestions,
new { @name = "help_practicalSuggestions"
})
Any idea what I am doing wrong here?
Rendered HTML:
<div>
<input data-val="true" data-val-required="The Provide practical suggestions for implementing change, e.g. step-by-step best practices field is required." id="ProvidePracticalSuggestions" name="ProvidePracticalSuggestions" type="checkbox" value="true" /><input name="ProvidePracticalSuggestions" type="hidden" value="false" />
<span class="field-validation-valid" data-valmsg-for="ProvidePracticalSuggestions" data-valmsg-replace="true"></span>
<label for="ProvidePracticalSuggestions">Provide practical suggestions for implementing change, e.g. step-by-step best practices</label>
</div>
EDIT on 09/07/2016
This will not work
But This will work
The trick is to use capital letter
"N"in"Name"I do not think this is Possible. You can not change the
nameattribute for a checkbox element when using the HTML Helper method. Out of curiousity, i looked into the MVC source code and found something interesting insideInputHelpermethod which is being called from theCheckBoxHelpermethod which is being called from theCheckBoxFormethodIt is calling the MergeAttribute method for “
type“, “name” and “value“. And this code is only for the Checkbox elementEDIT : Looked into the MergeAttribute method and this is how it is
So it is calling
MergeAttributeof theTagBuilderclass and it looks like thisAnd the the first
Ifcondition returns true and the innerifwill not return true because ( I guess)nameis present in theAttributescollection. So it will just execute thereturnstatement.Solution : Instead of using
Html.CheckBoxForhelper method, you might use theHtml.CheckBoxmethod.So your code will become
The first parameter is the name you want for the input element.
Also, as explained in one of the other answer , If you use
new { @Name="MyCustomName"}and It will generate the checkbox element with the name you are passing. But it will not generate the hidden input field with this name. your hidden field will still have the same name as your model property name.CheckboxForhelper method usually generate the hidden field to store the selected/unselected value of checkbox in this hidden field. So it is important that you should have both field’s(checkbox and it’s associated hidden field) name as same.So the best solution is to use
Html.CheckBoxhelper method. This will generate the proper name for the hidden field as well.