asp.net mvc - 根据Html.TextBoxF的条件设置disable属性
我想根据下面的asp.net MVC中的Html.TextBoxFor条件设置disable属性
@Html.TextBoxFor(model => model.ExpireDate, new { style = "width: 70px;", maxlength = "10", id = "expire-date" disabled = (Model.ExpireDate == null ? "disable" : "") })
该助手有两个输出禁用=“禁用”或禁用=“”。 两个主题都使文本框禁用。
如果Model.ExpireDate == null,我想禁用文本框,否则我想启用它
11个解决方案
75 votes
有效的方法是:
disabled="disabled"
浏览器也可以接受disabled="",但我建议您采用第一种方法。
现在我要建议你编写一个自定义HTML帮助程序,以便将这个禁用功能封装到一个可重用的代码段中:
using System;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
public static class HtmlExtensions
{
public static IHtmlString MyTextBoxFor(
this HtmlHelper htmlHelper,
Expression> expression,
object htmlAttributes,
bool disabled
)
{
var attributes = new RouteValueDictionary(htmlAttributes);
if (disabled)
{
attributes["disabled"] = "disabled";
}
return htmlHelper.TextBoxFor(expression, attributes);
}
}
您可以这样使用:
@Html.MyTextBoxFor(
model => model.ExpireDate,
new {
style = "width: 70px;",
maxlength = "10",
id = "expire-date"
},
Model.ExpireDate == null
)
你可以为这个助手带来更多智慧:
public static class HtmlExtensions
{
public static IHtmlString MyTextBoxFor(
this HtmlHelper htmlHelper,
Expression> expression,
object htmlAttributes
)
{
var attributes = new RouteValueDictionary(htmlAttributes);
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
if (metaData.Model == null)
{
attributes["disabled"] = "disabled";
}
return htmlHelper.TextBoxFor(expression, attributes);
}
}
所以现在你不再需要指定禁用的条件:
@Html.MyTextBoxFor(
model => model.ExpireDate,
new {
style = "width: 70px;",
maxlength = "10",
id = "expire-date"
}
)
Darin Dimitrov answered 2019-06-20T21:18:54Z
37 votes
实际上,内部行为是将匿名对象转换为字典。所以我在这些场景中所做的就是找一本字典:
@{
var htmlAttributes = new Dictionary
{
{ "class" , "form-control"},
{ "placeholder", "Why?" }
};
if (Model.IsDisabled)
{
htmlAttributes.Add("disabled", "disabled");
}
}
@Html.EditorFor(m => m.Description, new { htmlAttributes = htmlAttributes })
或者,斯蒂芬在这里评论道:
@Html.EditorFor(m => m.Description,
Model.IsDisabled ? (object)new { disabled = "disabled" } : (object)new { })
Shimmy answered 2019-06-20T21:19:25Z
22 votes
我喜欢达林方法。 但快速解决这个问题的方法,
Html.TextBox("Expiry", null, new { style = "width: 70px;", maxlength = "10", id = "expire-date", disabled = "disabled" }).ToString().Replace("disabled=\"disabled\"", (1 == 2 ? "" : "disabled=\"disabled\""))
user571646 answered 2019-06-20T21:19:49Z
11 votes
我使用一些扩展方法实现了它
public static MvcHtmlString IsDisabled(this MvcHtmlString htmlString, bool disabled)
{
string rawstring = htmlString.ToString();
if (disabled)
{
rawstring = rawstring.Insert(rawstring.Length - 2, "disabled=\"disabled\"");
}
return new MvcHtmlString(rawstring);
}
public static MvcHtmlString IsReadonly(this MvcHtmlString htmlString, bool @readonly)
{
string rawstring = htmlString.ToString();
if (@readonly)
{
rawstring = rawstring.Insert(rawstring.Length - 2, "readonly=\"readonly\"");
}
return new MvcHtmlString(rawstring);
}
然后....
@Html.TextBoxFor(model => model.Name, new { @class= "someclass"}).IsDisabled(Model.ExpireDate == null)
MurtuzaB answered 2019-06-20T21:20:19Z
9 votes
这已经晚了,但可能对某些人有所帮助。
我已经扩展了@ DarinDimitrov的答案,允许传递第二个对象,它接受任意数量的布尔html属性,如disabled="disabled" checked="checked", selected="selected"等。
仅当属性值为true时才会呈现属性,其他任何内容和属性都不会呈现。
自定义可重用的HtmlHelper:
public static class HtmlExtensions
{
public static IHtmlString MyTextBoxFor(this HtmlHelper htmlHelper,
Expression> expression,
object htmlAttributes,
object booleanHtmlAttributes)
{
var attributes = new RouteValueDictionary(htmlAttributes);
//Reflect over the properties of the newly added booleanHtmlAttributes object
foreach (var prop in booleanHtmlAttributes.GetType().GetProperties())
{
//Find only the properties that are true and inject into the main attributes.
//and discard the rest.
if (ValueIsTrue(prop.GetValue(booleanHtmlAttributes, null)))
{
attributes[prop.Name] = prop.Name;
}
}
return htmlHelper.TextBoxFor(expression, attributes);
}
private static bool ValueIsTrue(object obj)
{
bool res = false;
try
{
res = Convert.ToBoolean(obj);
}
catch (FormatException)
{
res = false;
}
catch(InvalidCastException)
{
res = false;
}
return res;
}
}
您可以这样使用:
@Html.MyTextBoxFor(m => Model.Employee.Name
, new { @class = "x-large" , placeholder = "Type something…" }
, new { disabled = true})
kooldave98 answered 2019-06-20T21:21:11Z
8 votes
如果您不使用html助手,您可以使用简单的三元表达式,如下所示:
value="@Model.Field" tabindex="0"
@(Model.IsDisabledField ? "disabled=\"disabled\"" : "")>
Andrei Tserakhau answered 2019-06-20T21:21:35Z
6 votes
我使用的一个简单方法是条件渲染:
@(Model.ExpireDate == null ?
@Html.TextBoxFor(m => m.ExpireDate, new { @disabled = "disabled" }) :
@Html.TextBoxFor(m => m.ExpireDate)
)
mfsumption answered 2019-06-20T21:21:59Z
6 votes
使用RouteValueDictionary解决了这个问题(可以正常工作,因为它基于IDictionary的htmlAttributes)和扩展方法:
public static RouteValueDictionary AddIf(this RouteValueDictionary dict, bool condition, string name, object value)
{
if (condition) dict.Add(name, value);
return dict;
}
用法:
@Html.TextBoxFor(m => m.GovId, new RouteValueDictionary(new { @class = "form-control" })
.AddIf(Model.IsEntityFieldsLocked, "disabled", "disabled"))
归功于[https://stackoverflow.com/a/3481969/40939]
Niels Bosma answered 2019-06-20T21:22:32Z
4 votes
另一种解决方案是在调用TextBoxFor之前创建Dictionary并传递该字典。 在字典中,仅在要删除文本框时才添加"disabled"密钥。 不是最好的解决方案,而是简单明了。
Kjell Rilbe answered 2019-06-20T21:22:57Z
2 votes
另一种方法是禁用客户端上的文本框。
在您的情况下,您只需要禁用一个文本框,但请考虑您需要禁用多个input,select和textarea字段的情况。
通过jquery +(因为我们不能依赖来自客户端的数据)更容易添加一些逻辑到控制器以防止这些字段被保存。
这是一个例子:
$(document).ready(function () {
disableAll();
}
function disableAll() {
var status = $('#document_Status').val();
if (status != 0) {
$("input").attr('disabled', true);
$("textarea").attr('disabled', true);
$("select").attr('disabled', true);
}
}
Dror answered 2019-06-20T21:23:38Z
2 votes
如果你不想使用Html Helpers看看我的解决方案
disabled="@(your Expression that returns true or false")"
它
@{
bool isManager = (Session["User"] as User).IsManager;
}
我认为更好的方法是在控制器中进行检查,并将其保存在视图内部可访问的变量(Razor引擎)中,以便制作the view free from business logic
Basheer AL-MOMANI answered 2019-06-20T21:24:17Z