control name in TextBoxFor in MVC3

前端 未结 5 1038
孤城傲影
孤城傲影 2020-12-11 04:45

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         


        
相关标签:
5条回答
  • 2020-12-11 05:04

    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

    0 讨论(0)
  • 2020-12-11 05:16

    Use TextBox instead of TextBoxFor

    @Html.TextBox("MyPreferedName", Model.SearchParams.someParam)
    
    0 讨论(0)
  • 2020-12-11 05:23

    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.

    0 讨论(0)
  • 2020-12-11 05:27
    @Html.TextBoxFor(model => model.attr, new { Name = "txt1" })
    

    Just Use "Name" instead of "name"

    0 讨论(0)
  • 2020-12-11 05:28

    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="" />
    
    0 讨论(0)
提交回复
热议问题