Kobi
Kobi

Reputation: 201

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="" />

Upvotes: 12

Views: 35720

Answers (6)

Kevin Farrugia
Kevin Farrugia

Reputation: 7489

If I understood your question correctly, you want to be able to prefix a string onto the Model's property name.

Therefore if you are in the view 'Account', you will get

AccountName

whilst in the view 'Test', you will get

TestName

If that is the case, I think your best bet is overriding the PartialFor extension method, similarly as is done here:

ASP.NET MVC partial views: input name prefixes

In this example, it will render

Account.Name and Test.Name

Upvotes: 0

u_1958148
u_1958148

Reputation: 383

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

Just Use "Name" instead of "name"

Upvotes: 12

enoshixi
enoshixi

Reputation: 309

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.

Upvotes: 4

enorl76
enorl76

Reputation: 2655

You should change your DisplayName attribute from "Name" to "UserName".

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

If you do that, you'll get what you're asking for.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039468

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; }

Upvotes: 2

Hadas
Hadas

Reputation: 10384

You can write:

@Html.TextBoxFor(model => model.Name, new { @id= "UserName",@Name="UserName" })

Upvotes: -2

Related Questions