How to create a readonly text using html helper in asp.net mvc?

后端 未结 6 1943
陌清茗
陌清茗 2020-12-15 17:54

I want to disable a textbox in the view. So I use following code:

<%= Html.TextBox(\"ID\", Model.ID, new { readonly=\"true\" })%>

or

相关标签:
6条回答
  • 2020-12-15 17:59

    Keep in mind a disabled TextBox will not be submitted with a html form, but a readonly TextBox will.

    MVC3 documentation shows the signature as Html.TextBox(string name, object value, object htmlAttributes) used above.

    0 讨论(0)
  • 2020-12-15 18:05

    If you are not forced to show a readonly textbox in your web page, consider using the @Html.DisplayFor helper: your output will be readonly (actually it will be just a text in a div) and will be part of the Model when the engine will model bind on submit.

    0 讨论(0)
  • 2020-12-15 18:08

    Try

    <%= Html.TextBox("ID", Model.ID, null, new { @readonly="true" })%>
    

    instead of

    <%= Html.TextBox("ID", Model.ID, new { @readonly="true" })%>
    

    If you check the documentation, you can see that the third parameter is not htmlAttributes, as you probably expected.

    You need to use the overload with four parameters.

    0 讨论(0)
  • 2020-12-15 18:11

    Try

    <%= Html.TextBox("ID", Model.ID, new { @readonly="readonly" })%>
    

    I'm not sure you have to use the overload with 4 parameters. You should be able to use the one with 3, but you need to append @ to the readonly since readonly is a keyword in C#. And setting @readonly to readonly is XHTML compliant.

    0 讨论(0)
  • 2020-12-15 18:12

    Taking advantage of the more up to date API you can use:

    Web Forms Engine:

    <%= Html.TextBoxFor(m => m.ID, new { @readonly = "readonly" }) %>
    

    Razor Engine:

    @Html.TextBoxFor(m => m.ID, new { @readonly = "readonly" })
    

    Cheers.

    0 讨论(0)
  • 2020-12-15 18:15

    Or this:

    <%= Html.TextBox("ID", Model.ID, new { @disabled="true" })%>
    
    0 讨论(0)
提交回复
热议问题