2011-12-08 14 views
4

フォームがロードされたときに値を持つすべてのフィールドを無効にしたい。 この例のようにオプションの無効な属性を設定する

<td>@Html.TextBoxFor(m => m.PracticeName, new { style = "width:100%", disabled = Model.PracticeName == String.Empty ? "Something Here" : "disabled" })</td> 

このようなインラインで記述したいと思います。私はif-elseを使用してコードを大きくしたくありません。 javascript/jqueryの使用も歓迎しません。

私はfalse/trueを書こうとしましたが、それはおそらくクロスブラウザではありません2.Mvcは "True"や "False"のような文字列に解析しました。 どうすればいいですか?

P.S.

public static class HtmlExtensions 
{ 
    public static IHtmlString TextBoxFor<TModel, TProperty>(
     this HtmlHelper<TModel> htmlHelper, 
     Expression<Func<TModel, TProperty>> ex, 
     object htmlAttributes, 
     bool disabled 
    ) 
    { 
     var attributes = new RouteValueDictionary(htmlAttributes); 
     if (disabled) 
     { 
      attributes["disabled"] = "disabled"; 
     } 
     return htmlHelper.TextBoxFor(ex, attributes); 
    } 
} 

次のように使用することができます::ヘルパーが明らかに取ることができる

@Html.TextBoxFor(
    m => m.PracticeName, 
    new { style = "width:100%" }, 
    Model.PracticeName != String.Empty 
) 

私は、ASP.NET MVC 3 :)

答えて

5

はカスタムヘルパーのための良い候補のように思える使用します追加のブール値を渡す必要はないが、式の値がdefault(TProperty)と等しいかどうかを自動的に判断し、disabled属性を適用するようにします。私はダーリンの答えを使用

@Html.TextBoxFor(
    m => m.PracticeName, 
    new { style = "width:100%" }.DisabledIf(Model.PracticeName != string.Empty) 
) 
+0

ありがとう、私は2番目の拡張メソッドを使用しました。 –

0

:あなたは標準TextBoxForヘルパーを使用することになり

public static class AttributesExtensions 
{ 
    public static RouteValueDictionary DisabledIf(
     this object htmlAttributes, 
     bool disabled 
    ) 
    { 
     var attributes = new RouteValueDictionary(htmlAttributes); 
     if (disabled) 
     { 
      attributes["disabled"] = "disabled"; 
     } 
     return attributes; 
    } 
} 

別の可能性としては、このような拡張メソッドです。しかし、data_my_custom_attributeになると、data-my-custom-attributeと表示されませんでした。だから私はこれを処理するためにDarinのコードを変更しました。

public static RouteValueDictionary DisabledIf(
    this object htmlAttributes, 
    bool disabled 
    ) 
{ 
    RouteValueDictionary htmlAttributesDictionary 
     = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); 

    if (disabled) 
    { 
     htmlAttributesDictionary["disabled"] = "disabled"; 
    } 
    return new RouteValueDictionary(htmlAttributesDictionary); 
} 
関連する問題