control name in TextBoxFor in MVC3

2019-01-19 16:23发布

问题:

Is it possible to control the name attribute of say a text boxt when using TextBoxFor?

this code in the view

@Html.TextBoxFor(m => m.SearchParams.someParam)

produce this

<input id="SearchParams_someParam" name="SearchParams.someParam" type="text" value="">

but I do not want my input name to be "SearchParams.someParam" and I wanted that to be something like

<input id="SearchParams_someParam" name="MyPreferedName" type="text" value="">

where the MyPreferedName comes from from some attributes the .SearchParams.someParam in the corresponding model.

Is this possible? I know @Html.TextBox does it but I do not want to hardcode the name in the view.

回答1:

@Html.TextBoxFor(model => model.attr, new { Name = "txt1" })

Just Use "Name" instead of "name"



回答2:

It seems as though the TextBoxFor method will not allow you to use the @name key as an htmlAttribute. This makes a little bit of sense because if it did allow you to override the HTML name attribute, the value would not get binded to your model properly in a form POST.

Instead of using...

@Html.TextBoxFor(x => Model.MyProperty, new { @name = "desired_name" }); // does not work

I ended up having to use...

@Html.TextBox("desired_name", Model.MyProperty); // works

I am not exactly sure why the first option does not work but hopefully this helps get around it.



回答3:

Use TextBox instead of TextBoxFor

@Html.TextBox("MyPreferedName", Model.SearchParams.someParam)


回答4:

Don't this work? @Html.TextBoxFor(m => m.SearchParams.someParam, new { id="my_id" }) although for your specific case it's be more like:

@Html.TextBoxFor(m => m.SearchParams.someParam, new { name = "MyPreferedName" })

Here you'll find the different overloads for the constructor of the InputExtensions.TextBoxFor in MVC3



回答5:

TextBoxFor doesn't allow the name attribute to be set. This workaround:

@Html.EditorFor(m => m.UserName, null, "user_name")

outputs:

<input class="text-box single-line" id="user_name" name="user_name" type="text" value="" />