基于Html.TextBoxFor条件设置禁用属性 [英] Set disable attribute based on a condition for Html.TextBoxFor
问题描述
我想基于Html.TextBoxFor在asp.net MVC像下面
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" : "") })
本助手有两个输出禁用=禁用或禁用=。这两个主题使文本框中禁用。
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"
浏览器也可以的接受的禁用=
但我会建议你第一种方法。
Browsers also might accept disabled=""
but I would recommend you the first approach.
现在这是说我会建议你为了封装编写自定义的HTML帮助这个的禁用的功能整合到一个可重用的一块code的:
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);
}
}
,你可以使用这样的:
which you could use like this:
@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屋!