14

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>
user547794
  • 14,263
  • 36
  • 103
  • 152
  • is it displaying anything? throwing an error? – Brian Jul 24 '12 at 19:45
  • No, not seeing an error. It's just not changing the name of the checkbox. I swear I've done this before... – user547794 Jul 24 '12 at 19:48
  • 1
    have you try using it with out the @ symbol on name – HatSoft Jul 24 '12 at 19:50
  • 2
    For reference, that at (@) symbol is usually used just for the 'class' property — it is an escape character so it can use the reserved word (class) as a property name. Most other common HTML attributes don't conflict, so they don't need the escape character. – Jon Adams Jul 24 '12 at 19:57
  • @user547794 so you are after the attribute name and you want the N of the attribute to be capital. Correct? – HatSoft Jul 24 '12 at 20:01
  • Not necessarily, I just want it to override the "name" attribute that MVC adds by default. – user547794 Jul 24 '12 at 20:02
  • @user547794: It will not. Check my answer why – Shyju Jul 24 '12 at 20:14
  • @user547794 although this is from a long while ago, in case you were wondering, my answer below should actually solve your need. :) – tklives Mar 15 '16 at 17:13

8 Answers8

30

EDIT on 09/07/2016

This will not work

@Html.CheckBoxFor(model => model.ProvidePracticalSuggestions,
                                              new { name = "help_practicalSuggestions"   })

But This will work

@Html.CheckBoxFor(model => model.ProvidePracticalSuggestions,
                                              new { Name = "help_practicalSuggestions"   })

The trick is to use capital letter "N" in "Name"


I do not think this is Possible. You can not change the name attribute for a checkbox element when using the HTML Helper method. Out of curiousity, i looked into the MVC source code and found something interesting inside InputHelper method which is being called from the CheckBoxHelper method which is being called from the CheckBoxFor method

enter image description here

It is calling the MergeAttribute method for "type", "name" and "value". And this code is only for the Checkbox element

EDIT : Looked into the MergeAttribute method and this is how it is

public void MergeAttribute(string key, string value)
{
    bool flag = false;
    this.MergeAttribute(key, value, flag);
}

So it is calling MergeAttribute of the TagBuilder class and it looks like this

public void MergeAttribute(string key, string value, bool replaceExisting)
{
    if (!string.IsNullOrEmpty(key))
    {
        if (replaceExisting || !this.Attributes.ContainsKey(key))
        {
            this.Attributes[key] = value;
        }
        return;
    }
    else
    {
        throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "key");
    }
}

And the the first If condition returns true and the inner if will not return true because ( I guess) name is present in the Attributes collection. So it will just execute the return statement.

Solution : Instead of using Html.CheckBoxFor helper method, you might use the Html.CheckBox method.

public static MvcHtmlString CheckBox(
    this HtmlHelper htmlHelper,
    string name
)

So your code will become

@Html.CheckBox("help_practicalSuggestions",Model.ProvidePracticalSuggestions)

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. CheckboxFor helper 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.CheckBox helper method. This will generate the proper name for the hidden field as well.

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • 2
    This is still valid in .NET 4.6 and it seems semantically stupid that "n" and "N" make all the difference. – edwardrbaker Mar 14 '17 at 18:22
  • Just tried this and it worked for me. But I won't used because it seems to be forbidden in the HTML5 spec. and could cause trouble in the furutre. See this SO question: https://stackoverflow.com/questions/26341507/can-an-html-element-have-the-same-attribute-twice – Daniel Hillebrand Jul 30 '17 at 09:58
16

Can't do that. The whole point of CheckBoxFor is to auto-generate name. If you want your own name, use

@Html.CheckBox("help_practicalSuggestions", Model.ProvidePracticalSuggestions)
Sergei Rogovtcev
  • 5,804
  • 2
  • 22
  • 35
16

Actually, all you have to do is use "@Name" (with a uppercase N) as shown below, and everything should work out just fine! :)

@Html.CheckBoxFor(
model => model.ProvidePracticalSuggestions,
         new { @Name = "help_practicalSuggestions"})

Cheers!

tklives
  • 469
  • 6
  • 15
  • 1
    In my tests that adds a second name field, making the input form invalid. It does work sometimes depending on the names! – Kam Jul 23 '14 at 05:04
  • @Kam - I have to do this on a fairly regular basis when using complex view models so the name doesn't end up being a grossly huge string of underscores and words, and have never had an issue with a duplicate name attribute being created...very strange! I will have to look into that more! – tklives Sep 12 '14 at 14:18
  • 1
    You life saver. As Tim says the name generated by CheckBoxFor is sometimes incorrect. – Stonedecroze Feb 23 '16 at 16:36
1

You don't need the @ symbol in name

@Html.CheckBoxFor(
model => model.ProvidePracticalSuggestions, 
new { name = "help_practicalSuggestions" })
HatSoft
  • 11,077
  • 3
  • 28
  • 43
  • Hmm... Tried this, it's still not overwriting the changes. If I use "Name" with a capital N it adds a "Name" in addition to the "name attribute. Why doesn't "name" overwrite the existing name? – user547794 Jul 24 '12 at 19:54
  • @user547794 Please show me the rendered html from view source – HatSoft Jul 24 '12 at 19:56
  • @user547794 please try this for me instead of "@name" try using id="help_practicalSuggestions" – HatSoft Jul 24 '12 at 20:03
  • Changing the Id worked fine. So weird, why can't I change the name? – user547794 Jul 24 '12 at 20:06
  • @user547794 reason it is giving priority to id instead of name, ill update my answer – HatSoft Jul 24 '12 at 20:07
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/14364/discussion-between-hatsoft-and-user547794) – HatSoft Jul 24 '12 at 20:14
  • @user547794 you will have to use "@Html.CheckBox" as per MSDN http://msdn.microsoft.com/en-us/library/dd460245.aspx – HatSoft Jul 24 '12 at 20:18
  • I appreciate the explanation. I need to be able to specify the name of the inputs in order to interact with a javascript API. Html.CheckBox gives me an "Object reference not set to an instance of an object." error – user547794 Jul 24 '12 at 21:11
0

Try without the @:

@Html.CheckBoxFor(model => model.ProvidePracticalSuggestions, new { name = "help_practicalSuggestions" })
Shane Fulmer
  • 7,510
  • 6
  • 35
  • 43
0

Just create a temp variable and pass that in the lambda expression.

@{var help_practicalSuggestions = Model.ProvidePracticalSuggestions; } 
@Html.CheckBoxFor(model => help_practicalSuggestions)

Update

Serg Rogovtsev is actually right. The '...For' version of the helper function provides the name attribute for you automatically.

jschell12
  • 61
  • 5
0

In CheckBoxFor helper we bind the control to property using expression. The property name is used to set the name attribute of the control.

@Html.CheckBoxFor(model => model.IsMarried)

When I bind the model property with the checkbox, it assigns the name attribute of the control with property name itself as shown below :

Rendered HTML:

<input id="IsMarried" name="IsMarried" type="checkbox" value="true" />
<input name="IsMarried" type="hidden" value="false" />

You can propbably use CheckBox helper to give name attribute or you can create your own custom helper method where you can assign attributes as you wish.

For more additional information visit :

http://20fingers2brains.blogspot.in/2013/02/html-checkboxfor-helper-in-mvc3-razor.html

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
Karan
  • 1
0

First add filter to your model that called DisplayAttribute

[DisplayAttribute(Name = "Some Text")]
public bool IsChecked { get; set; }

And you can use Label for model

@Html.LabelFor(model => model.PropertyName)
Rahul
  • 5,603
  • 6
  • 34
  • 57