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

Solution 1:

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" })

Solution 2:

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.

Solution 3:

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

 @Html.EditorFor(expression, null, name)

Solution 4:

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")