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.
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" })
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.
EditorFor has an overload where you can supply the name
attribute as a parameter:
@Html.EditorFor(expression, null, name)
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With