control name in TextBoxFor in MVC3
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 f开发者_运维知识库rom 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.
@Html.TextBoxFor(model => model.attr, new { Name = "txt1" })
Just Use "Name" instead of "name"
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.
Use TextBox instead of TextBoxFor
@Html.TextBox("MyPreferedName", Model.SearchParams.someParam)
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="" />
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
精彩评论