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

11

115

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.

Argueta answered 19/5, 2011 at 11:23 Comment(4)
What is the data type of 'Data'Immoral
Duplicate of #6921435 and #6064863Left
Those questions are asking something slightly different. Also - this is the older of the three, so I think you mean duplicated by.Argueta
https://mcmap.net/q/189558/-set-quot-id-quot-and-quot-name-quot-for-htmleditorforOruro
G
257

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" })
Glasgo answered 14/7, 2013 at 9:36 Comment(13)
Case-sensitive it is @highwingers, this tiny detail has the potential to save hours.Glasgo
Overkill.. Name but id X_XMonosyllable
@Vladimirs, sorry, what do you mean?Glasgo
Weird, "id" is not case-sensitive (works fine with Id and id) but "name" isn't.Monosyllable
With ASP.NET 4, providing Name results in two attributes, Name and name, and the model binder uses the name.Redhead
But handling two different properties whose names differ only by case is a recipe for a maintenance nightmare.....Ingot
+1 bc this worked. still looking for a way to tell Chrome to put last name in a field instead of email.Britisher
@Brad, can you describe the problem you are facing? Maybe create a new question here on stackoverflow?Glasgo
@Anar, building a register form, put in the name attributes, but Chrome is still putting email in the email AND lname fields. I might get around to it, but right now, I'm just working on the stuff that's quick to fix or flat out broken. Deadlines and all :-\Britisher
@Brad, maybe Chrome is overwriting the last name field by using the autofill feature of the browser. Good luck anyway.Glasgo
Works, but isn't documented, so it's liable to change... I'm afraid to use this "feature" unless someone has an official reference?Brick
Really old, may help someone, to make the validation to work @Html.ValidationMessageFor(x => x.Data, string.Empty, new { data_valmsg_for = Model.Key + "_Data" }).Indicate
Anyone know why this would not work in asp.net core mvc 7?Clardy
I
44

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.

Ingot answered 19/5, 2011 at 12:1 Comment(3)
This looks like the winner! Beautiful.Argueta
Yeah they hid that one nicely didn't they :)Ingot
This just saved me some headache and code duplication.Aurea
R
14

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

 @Html.EditorFor(expression, null, name)
Readjust answered 18/5, 2015 at 14:57 Comment(2)
Would have saved me hours if I found this hours ago, hahaAdvertise
Interesting, but there is no overload for the name attribute for similar helpers like DropDownListFor, you have to specify it in the html attributes parameter (with a capital N in Name).Puzzler
R
9

It is called Microsoft GOTCHA...

Use the name in caps, like this

@Html.TextBoxFor(m => m.Reply.Answer, new { Name = "Whatyouwant" })
Rocker answered 18/11, 2017 at 2:55 Comment(3)
It really makes the difference, if you use @name, it will not get overridden. Very hard to figure out. ThanksMildew
Duplicate answer, and doesn't work in Core 3.1.Levity
@SteveSmith It's an old answer, CORE was not there in 2017, MVC rendering engine has been changed entirely.Rocker
I
8

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")
Immoral answered 19/5, 2011 at 11:55 Comment(0)
P
7

ben's answer got me what I was looking for except you need to wrap in in Html.Raw

@Html.Raw(Html.TextBoxFor(x => x.Data).ToString().Replace("Data", "NewData"))
Pickerel answered 19/2, 2012 at 3:0 Comment(0)
W
4

a little bit "unpretty"=), try:

@Html.TextBoxFor(x => x.Data).ToString().Replace("Data", "NewData")
Wayfarer answered 19/5, 2011 at 11:43 Comment(2)
Seems like a nice easy way to do it. If a little hacky :-)Argueta
umm, this way, wouldnt you rather just take normal Html.TexBox.. since any static typing is gone anyway after the replaceAvila
R
2

For me, it works! I hope that help!

@Html.EditorFor(model => model.Nome, new { htmlAttributes = new { @class = "form-control", @maxlength = "80", @id = "NomeFilter", @Name = "NomeFilter" } })
Repute answered 29/11, 2016 at 18:4 Comment(0)
A
1
@Html.EditorFor(Model => Model.Something, "name", "name", new {@class = "form-control" })

Not sure which of those two string parameters in the middle do the work, but it worked only when I typed both of them.

Aphotic answered 7/1, 2018 at 14:47 Comment(2)
It's Id and Name. this worked for me. I went through all above answers and non of them worked, but this 1. Thanks.Homegrown
public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName, string htmlFieldName, object additionalViewData);. No idea what templateName is supposed to be, so I used null. For htmlFieldName I used the name of the parameter (in my case "ipmi" instead of "IPMI"). That did the trick for me.Microbalance
L
1

For this example, I was disabling form fields based on permissions, but still showing them. I had a hidden field to send the value to the controller, but wanted a different field name in the EditorFor. First param after model value represents the "name" property, second is the new name.

@Html.EditorFor(m => m.UserName, "name", "UserNameDisabled", new { htmlAttributes = new { @class = "form-control", @disabled = "disabled"} });

Results in:

<input class="form-control text-box single-line" disabled="disabled" id="UserNameDisabled" name="UserNameDisabled" type="text" value="someEnteredValue" /> 
Latif answered 2/2, 2018 at 14:57 Comment(0)
S
1

Keep it simple, your already providing the ID you should simply be able to use the method "TextBox" instead of "TextBoxFor" and it will work fine client side and server side. In addition, although the accepted answer will work but will produce duplicate Name attributes on your tag if you inspect it using a browser. The below solution does not have that problem.

MvcHtmlString Html.TextBox(string name, string value, object htmlAttributes)

@Html.TextBox(Model.Key + "_Data", Model.Key, new { id = Model.Key + "_Data" }
Shoer answered 13/6, 2019 at 21:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.