Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using Html.TextBoxFor, add the name of the model as prefix to id

I have an asp mvc 3 project When I use

@Html.TextBoxFor(model => model.Name)

the TexBoxFor render as

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

my model is "UserModel" :

[DisplayName("Name")]
public string Name{ get; set; }

Is there a way to add to the name of the model as prefix in the id? maybe some attribute?

I want that the text box will render as

<input id="UserName" name="UserName" type="text" value="" />
like image 549
Kobi Avatar asked Jan 02 '12 08:01

Kobi


People also ask

What is the difference between using HTML TextBoxFor and HTML TextBox?

Both of them provide the same HTML output, “HTML. TextBoxFor” is strongly typed while “HTML. TextBox” isn't. Below is a simple HTML code which just creates a simple textbox with “CustomerCode” as name.

How do you make a TextBoxFor ReadOnly?

The TextBoxes can be made ReadOnly by setting the HTML ReadOnly attribute using the HtmlAttributes parameter in Html. TextBox and Html. TextBoxFor helper functions.


3 Answers

If you don't want to render the input as described in your model, you probably don't want to be using the Html.TextBoxFor helper.

Try Html.TextBox instead. You can provide it with the exact values you're looking for:

@Html.TextBox("UserName", Model.Name, new { id = "UserName" })

Don't forget you can also forget the helpers and use plain old html:

<input id="UserName" name="UserName" type="text" value="@Model.Name" />

Warning: When using either of these methods and the default model binder, the value of this input will not be bound back to your model correctly when submitting back the data.

like image 166
enoshixi Avatar answered Oct 04 '22 03:10

enoshixi


@Html.TextBoxFor(model => model.attr, new { Name = "txt1" })

Just Use "Name" instead of "name"

like image 45
u_1958148 Avatar answered Oct 04 '22 03:10

u_1958148


The TextBoxFor helper uses the lambda expression that is passed as first argument to calculate the name of the input field. So if you want the generated input field to be called UserName, simply rename the property in your view model:

[DisplayName("Name")]
public string UserName { get; set; }
like image 37
Darin Dimitrov Avatar answered Oct 04 '22 02:10

Darin Dimitrov