chobo2
chobo2

Reputation: 85875

Why can't I specify a `name` attribute in an ASP.NET MVC form using Html.Helpers?

I am playing around with the ASP.NET MVC Html.Helpers and I noticed that say for instance:

Html.Textbox("test");  

will render the name attribute to "name=test" and the id tag will be "id=test"

But when I do this:

<%= Html.TextBox("go", null, new { @name = "test2", @id = "test2", @class = "test2" })%>

id will be "id=test2" but name will be "name=go"

Why does it not get overridden?

I also don't really still understand what the name tag actually does. I don't think I ever even used.

P.S

I am aware that "name" and "id" probably don't need to be escaped only "class" does since it is a keyword but I just do it for all of them just so I don't forget to do it or have to even remember if something is a keyword or not.

Upvotes: 2

Views: 2607

Answers (4)

Baunuts
Baunuts

Reputation: 21

Not sure it will help the asker but you need to use the correct casing. To set "name" attribute use:

<%= Html.TextBox("go", null, new { Name = "test2", @id = "test2", @class = "test2" })%>

Upvotes: 2

Eduardo Molteni
Eduardo Molteni

Reputation: 39453

Because it is a "Helper" helping you not to type the name in the 90% of the cases when you create a textbox.

You are free to not use them and just type:

<input type="textbox" 
       name="theNameIReallyWant" 
       value="<%= model.theNameOfThePropertyInTheModel %>">

or better yet, create your own TextBoxWithCustomName helper

Upvotes: 1

&#199;ağdaş Tekin
&#199;ağdaş Tekin

Reputation: 16661

The name attribute is used when accessing that form element's value on the server side. Like so :

string val = Request.Name["go"];

As for specifying the name attribute, well that's what the first parameter of the Html.TextBox method is there for.

Upvotes: 3

nothrow
nothrow

Reputation: 16168

ID is unique identifier in DOM tree, name is identifier within form, and it doesn't need to be unique, name is used after submitting the form.

Upvotes: 1

Related Questions