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!

1

4 Answers 4

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=""> 
Sign up to request clarification or add additional context in comments.

3 Comments

Using ASP.NET MVC 3, '@Html.TextBoxFor(m => m.UserName, new { Name = "user_name" })' produces '<input Name="user_name" id="UserName" name="UserName" type="text" value="" />' (both Name and name attributes).
It works in MVC4 as well, rendering <input name="txt1" id="txt1" readonly="True" type="text" value="">
Confirmed in MVC2 as well.
10

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

@Html.TextBoxFor(model => model.Property, new { Name = "myName" })

1 Comment

Wow I've had this problem for ages, name wouldn't work but Name did! It even works for Id.
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"})

2 Comments

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.
@IsaacLlopis: check my answer and be surprised... :) what a capital letter can do!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.