Html 在剃刀视图中启用和禁用文本框 (ASP.Net MVC 3)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6596665/
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
Enabling & disabling a textbox in razor view (ASP.Net MVC 3)
提问by Biki
I want to Enable or Disable a textbox based on the value (Model.CompanyNameEnabled
).
我想根据值 ( Model.CompanyNameEnabled
)启用或禁用文本框。
The below code is not working. Please rectify.
下面的代码不起作用。请纠正。
@{
string displayMode = (Model.CompanyNameEnabled) ? "" : "disabled = disabled";
@Html.TextBox("CompanyName", "", new { displayMode })
}
回答by archil
@{
object displayMode = (Model.CompanyNameEnabled) ? null : new {disabled = "disabled" };
@Html.TextBox("CompanyName", "", displayMode)
}
You should pass htmlAttribute as anonymous object, with property names = html attribute names, property values = attribute values. Your mistake was that you were passing string instead of name=value pair
您应该将 htmlAttribute 作为匿名对象传递,属性名称 = html 属性名称,属性值 = 属性值。你的错误是你传递的是字符串而不是名称=值对
回答by user1985065
<input id="textbox1" type="text" @{@((Model.CompanyNameEnabled) ? null : new { disabled = "disabled" })}; />
<input id="textbox1" type="text" @{@((Model.CompanyNameEnabled) ? null : new { disabled = "disabled" })}; />
Haven't tested it, but should work
没有测试过,但应该可以
回答by ransems
A simple approach:
一个简单的方法:
@Html.TextBoxFor(x => x.Phone, new { disabled = "disabled", @class = "form-control" })
@Html.TextBoxFor(x => x.Phone, new { disabled = "disabled", @class = "form-control" })
回答by Mr Tambourine Man
As is already mentioned in this thread the suggested answer doesn't work in MVC5 anymore. There's actually an easy two step solution to that problem.
正如本线程中已经提到的,建议的答案不再适用于 MVC5。这个问题实际上有一个简单的两步解决方案。
- Assign a class to the HTML inputs you want to be disabled / enabled (id will do for a single item just as fine of course). In the example below I assigned a class 'switch-disabled'to the input.
- 为您想要禁用/启用的 HTML 输入分配一个类(id 对单个项目也同样适用)。在下面的示例中,我为输入分配了一个“开关禁用”类。
@Html.TextBox("CompanyName", "", new { htmlAttributes = new { @class = "form-control switch-disable" } })
- Use javascript(jquery) to enable / disable the disabledparameter in HTML. In my example below I do this at the page load.
- 使用 javascript(jquery) 启用/禁用HTML 中的禁用参数。在下面的示例中,我在页面加载时执行此操作。
<script>
$(document).ready(() => {
if(@Model.CompanyNameEnabled)
{
$('.switch-disable').attr("disabled", false);
}else{
$('.switch-disable').attr("disabled", true);
}
});
</script>