根据 Html.TextBoxFor 的条件设置禁用属性 [英] Set disable attribute based on a condition for Html.TextBoxFor
问题描述
我想根据如下所示的 asp.net MVC 中 Html.TextBoxFor 的条件设置禁用属性
I want to set disable attribute based on a condition for Html.TextBoxFor in asp.net MVC like below
@Html.TextBoxFor(model => model.ExpireDate, new { style = "width: 70px;", maxlength = "10", id = "expire-date" disabled = (Model.ExpireDate == null ? "disable" : "") })
这个助手有两个输出 disabled="disabled " 或 disabled="".两个主题都使文本框禁用.
This helper has two output disabled="disabled " or disabled="". both of theme make the textbox disable.
如果 Model.ExpireDate == null 我想禁用文本框,否则我想启用它
I want to disable the textbox if Model.ExpireDate == null else I want to enable it
推荐答案
有效的方式是:
disabled="disabled"
浏览器也可能接受disabled=""
,但我建议您使用第一种方法.
Browsers also might accept disabled=""
but I would recommend you the first approach.
既然如此,我建议您编写一个自定义 HTML 帮助程序,以便将此禁用功能封装到可重用的代码段中:
Now this being said I would recommend you writing a custom HTML helper in order to encapsulate this disabling functionality into a reusable piece of code:
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<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> 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<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> 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);
}
}
这样你就不再需要指定禁用条件了:
so that now you no longer need to specify the disabled condition:
@Html.MyTextBoxFor(
model => model.ExpireDate,
new {
style = "width: 70px;",
maxlength = "10",
id = "expire-date"
}
)
这篇关于根据 Html.TextBoxFor 的条件设置禁用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!