Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3: Override "name" attribute with TextBoxFor

Is it possible when using Html.TextBoxFor to override the name attribute?

I have tried with no success. I need to use TextBoxFor to get client side validation to work, however for reasons I won't go into I need the name of the textbox to be different from the generated one.

I have tried the following:

@Html.TextBoxFor(x => x.Data, new { name = Model.Key + "_Data", id = Model.Key + "_Data" })

Which works for ID but not name. Is this possible?

Update: Looking into the code for TextBoxFor. It doesn't look like there is an easy way. Hopefully someone can prove me wrong.

like image 803
Rob Stevenson-Leggett Avatar asked May 19 '11 11:05

Rob Stevenson-Leggett


4 Answers

Rob, actually there is a much simpler way. Instead of name, use Name:

@Html.TextBoxFor(x => x.Data, new { Name = Model.Key + "_Data", id = Model.Key + "_Data" })
like image 188
anar khalilov Avatar answered Oct 20 '22 00:10

anar khalilov


Are you asking this because you want to apply a prefix to the name? If so, you can do this by setting ViewData.TemplateInfo.HtmlFieldPrefix in your Controller.

I learnt a lot about this stuff from Brad Wilson's blog.

like image 30
James McCormack Avatar answered Oct 19 '22 23:10

James McCormack


EditorFor has an overload where you can supply the name attribute as a parameter:

 @Html.EditorFor(expression, null, name)
like image 14
Protector one Avatar answered Oct 20 '22 01:10

Protector one


Try EditorFor. you can pass string as template name if you want to make sure textbox is rendered even if property type is not string. If property is string already, it does not need templatename explicitly to render textbox, so you can pass null. Note that it does not require id parameter explicitly, it will infer it from element name. And all the validation things are still active with EditorFor

 @Html.EditorFor(x => x.Data, "string", Model.Key + "_Data")
like image 8
archil Avatar answered Oct 20 '22 00:10

archil