control name in TextBoxFor in MVC3

前端 未结 5 1040
孤城傲影
孤城傲影 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: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.

提交回复
热议问题