title: Conditionally disable Html.DropDownList
body: <p>How can I change this DropDownList declaration so that the disabled attribute is enable/disabled conditionally?</p>
  
  <pre><code>&lt;%= Html.DropDownList("Quantity", new SelectList(...), new{@disabled="disabled"} %&gt;
  </code></pre>
  
  <p>non-working example:</p>
  
  <pre><code>&lt;%= Html.DropDownList("Quantity", new SelectList(...), new{@disabled=Model.CanEdit?"false":"disabled"} %&gt;
  </code></pre>
  
  <p>p.s. adding an if condition around the entire statement is not a desired approach :)</p>
  
  <p><strong>EDIT:</strong> based on <a href="https://stackoverflow.com/questions/233711/add-property-to-anonymous-type-after-creation/4416536#4416536">this</a> extension method from another question I came up with the following extension:</p>
  
  <pre><code>public static IDictionary&lt;string, object&gt; Disabled (this object obj, bool disabled)
  {
    return disabled ? obj.AddProperty ("disabled", "disabled") : obj.ToDictionary ();
  }
  </code></pre>
  
  <p>which can then be used as</p>
  
  <pre><code>&lt;%= Html.DropDownList("Quantity", new SelectList(...), new{id="quantity"}.Disabled(Model.CanEdit) %&gt;
  </code></pre>