Asp.net-Mvc

根據 Html.TextBoxFor 的條件設置禁用屬性

  • July 12, 2011

我想根據 asp.net MVC 中 Html.TextBoxFor 的條件設置禁用屬性,如下所示

@Html.TextBoxFor(model => model.ExpireDate, new { style = "width: 70px;", maxlength = "10", id = "expire-date" disabled = (Model.ExpireDate == null ? "disable" : "") })

這個助手有兩個輸出 disabled=“disabled” 或 disabled=""。兩個主題都使文本框禁用。

如果 Model.ExpireDate == null 我想禁用文本框,否則我想啟用它

有效的方法是:

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<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);
   }
}

這樣現在您不再需要指定禁用條件:

@Html.MyTextBoxFor(
   model => model.ExpireDate, 
   new { 
       style = "width: 70px;", 
       maxlength = "10", 
       id = "expire-date" 
   }
)

引用自:https://stackoverflow.com/questions/6660146