asp.net-mvc 如何在 asp.net mvc 中使用 html helper 创建只读文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1153912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a readonly text using html helper in asp.net mvc?
提问by KentZhou
I want to disable a textbox in the view. So I use following code:
我想禁用视图中的文本框。所以我使用以下代码:
<%= Html.TextBox("ID", Model.ID, new { readonly="true" })%>
or
或者
<%= Html.TextBox("ID", Model.ID, new { enable="false" })%>
Both of them don't work. what's the solution?
他们两个都不起作用。解决办法是什么?
回答by Brandon
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.
我不确定您是否必须使用带有 4 个参数的重载。您应该可以使用带有 3 的那个,但是您需要将 @ 附加到 readonly,因为 readonly 是 C# 中的一个关键字。将 @readonly 设置为 readonly 是 XHTML 兼容的。
回答by mookid8000
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.
如果您查看文档,您会发现第三个参数并非htmlAttributes如您所料。
You need to use the overload with four parameters.
回答by Ikaso
Taking advantage of the more up to date API you can use:
利用您可以使用的最新 API:
Web Forms Engine:
网页表单引擎:
<%= Html.TextBoxFor(m => m.ID, new { @readonly = "readonly" }) %>
Razor Engine:
剃须刀引擎:
@Html.TextBoxFor(m => m.ID, new { @readonly = "readonly" })
Cheers.
干杯。
回答by Paul Syfrett
Keep in mind a disabledTextBox will not be submitted with a html form, but a readonlyTextBox will.
请记住,禁用的TextBox 不会与 html 表单一起提交,但只读的TextBox 会。
MVC3 documentationshows the signature as Html.TextBox(string name, object value, object htmlAttributes) used above.
MVC3文档将签名显示为上面使用的 Html.TextBox(string name, object value, object htmlAttributes)。
回答by s0nica
If you are not forced to show a readonly textbox in your web page, consider using the @Html.DisplayForhelper: 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.
如果您没有被迫在您的网页中显示只读文本框,请考虑使用@Html.DisplayFor帮助程序:您的输出将是只读的(实际上它只是一个 div 中的文本)并且在引擎将模型绑定时将成为模型的一部分在提交。
回答by Hobbis
Or this:
或这个:
<%= Html.TextBox("ID", Model.ID, new { @disabled="true" })%>

