Rob Stevenson-Leggett Rob Stevenson-Leggett - 3 days ago 6
C# Question

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.

Answer

Would you be wanting to apply a prefix? For that, you can set ViewData.TemplateInfo.HtmlFieldPrefix in your Controller.

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

Comments