2012-02-27 19 views
0

追加のパラメータ()

<input style="width:50px;" type="text" id="blah" value="@model.value1" @if(model.id!=1){ <text>disabled</text>}/>

これは、基本的には、特定の状況下で無効になっているテキストボックスを示しています。 これをよりmvcに優しい方法に置き換えることにしました。

@Html.TextBoxFor(m => model.value1, new { id = "blah" })

でもない無効な属性を追加する方法がわから(動的に)私はそれがnew{}disabled=true値を追加することにより、静的にeasillyそれを行うために取得することができます。

私はこれを使用してみました:

@if (<condition>) { var disable = true; } @Html.TextBoxFor(m => model.value1, new { id = "blah", disabled = disable })

しかし、これもうまくいきませんでした。私はここに正しいアプローチを取っていますか?

答えて

3
@{ 
    var attributes = new Dictionary<string, object> 
    { 
     { "id", "blah" } 
    }; 
    if (<condition>) 
    { 
     attributes["disabled"] = "disabled"; 
    } 
} 
@Html.TextBoxFor(m => model.value1, attributes) 

「無効」と「真」他人に満足している明らかにそれは地獄のように醜いだとあなたもそのようなあなたのビューを汚染することを考えてはいけません。

public static class HtmlExtensions 
{ 
    public static IHtmlString MyTextBoxFor<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ヘルパー書くでしょう。これは細かい検証

@Html.MyTextBoxFor(m => model.value1, new { id = "blah" }, <condition>) 
+0

ありがとう、カスタムHtmlHelpersに慣れています。本当に便利な情報! – JustAnotherDeveloper

1

あなたは上記の無効化とスコープの問題は、if文の範囲外に存在しない、

私の勧告は、このあるある:

@Html.TextBoxFor(m => model.value1, new { id = "blah", disabled = (<condition>) }) 

EDIT:あなたが使用することができます

@Html.TextBoxFor(m => model.value1, new { id = "blah", disabled = (<condition>) ? "disabled" : "" }) 

ボーの代わりに無効の単語を挿入する場合は、オールは、メモリから、これはちょっと、いくつかの設定、ブラウザ固有のものです

+0

を、私は「無効」に単語を使用してイムとして考えます自動的にボックスを無効にします。 – JustAnotherDeveloper

+0

私の編集を見ると、インラインで三項演算子を使ってif文に基づいて異なる値を与えることができます。 –

+0

無効なキーワードは自動的に入力を無効にします – hjgraca

関連する問題