ASP.NET MVC 3: Override “name” attribute with TextBoxFor

前端 未结 11 1462
臣服心动
臣服心动 2020-11-28 05:41

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 vali

相关标签:
11条回答
  • 2020-11-28 06:14
    @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.

    0 讨论(0)
  • 2020-11-28 06:15

    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")
    
    0 讨论(0)
  • 2020-11-28 06:16

    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" }
    
    0 讨论(0)
  • 2020-11-28 06:24

    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" })
    
    0 讨论(0)
  • 2020-11-28 06:27

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