6

I want to manually define id and name for textbox like that:

<%: Html.TextBoxFor(model => model.Name, new { @id = "txt1", @name = "txt1" })%>

But only the id is changed, not the name attribute, why?

<input id="txt1" name="Name" type="text" value="">

Thank you!

Leniel Maccaferri
  • 97,176
  • 43
  • 357
  • 461
Tuizi
  • 1,553
  • 3
  • 20
  • 34
  • Duplicate of http://stackoverflow.com/questions/6920935/control-name-in-textboxfor-in-mvc3 and http://stackoverflow.com/questions/6057865/asp-net-mvc-3-override-name-attribute-with-textboxfor – Fernando Correia Aug 20 '12 at 14:23

4 Answers4

17

This is ok:

<%: Html.TextBoxFor(model => model.Name, new { Name = "txt1" })%> 

Do you write "Name" instead of "name"?

Output:

<input  name="txt1" type="text" value=""> 
Michael Myers
  • 184,092
  • 45
  • 284
  • 291
sandro
  • 187
  • 1
  • 2
10

Actually you can... just use Name with first letter capitalized instead of name:

@Html.TextBoxFor(model => model.Property, new { Name = "myName" })
Leniel Maccaferri
  • 97,176
  • 43
  • 357
  • 461
5

You can't use the strongly typed lambda version for this, you'd need to use the older version

Html.TextBox("txt1",new {@id = "txt1"})
Paul Creasey
  • 27,719
  • 10
  • 52
  • 89
  • 1
    This is a solution, yet it is not "THE" solution. For instance, TextBoxFor() includes unobtrusive validation attributes depending on the attributes that decorate a given property and that are IClientValidatable. TextBox() doesn't. – Isaac Llopis Feb 07 '13 at 14:00
  • @IsaacLlopis: check my answer and be surprised... :) what a capital letter can do! – Leniel Maccaferri Aug 24 '13 at 07:49
1

If you still need to use TextBoxFor(), you can change the name of the property on your model, which should be easy if you're using dedicated ViewModels as is recommended. However I admit it's a recommendation I don't always follow myself.

Nick Albrecht
  • 16,167
  • 9
  • 67
  • 98