0

I tried several answers posted on stackoverflow. However, the following doesn't seem to work:

@Html.TextArea("Comments", Model.Comments, Model.ReadOnly ? new { @disabled = "disabled"} : null)

I also tried:

@Html.TextArea("Comments", Model.Comments, Model.ReadOnly ? new { disabled = "disabled"} : null)

Any idea what am I doing wrong?

3 Answers3

0

I don't think that MVC likes a null here. What you need as a third parameter (which expects object) is a default empty anonymous instance instead of null:

Model.ReadOnly ? (object)new { disabled = "disabled" } : (object)new { }
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
0

I would use a custom variable to set it. I don't think the conditional is acceptable in the arguments of the HtmlHelper.

@{
    var htmlAttributes = Model.ReadOnly ? new { disabled = "disabled" } : null;
}

@Html.TextArea("Comments", Model.Comments, htmlAttributes)
Joel Etherton
  • 37,325
  • 10
  • 89
  • 104
  • I am going to try that! Any idea if I can add similar parameters to BOTH the true and false conditions? Without mentioning that in both – user5975648 Feb 24 '16 at 21:37
  • As long as the result is a valid collection of attributes you should be able to construct it that way. – Joel Etherton Feb 24 '16 at 21:43
0

Try wrapping your ternary operation in parentheses

@Html.TextArea("Comments", Model.Comments, (Model.ReadOnly ? new { @disabled = "disabled"} : null) )
randyh22
  • 463
  • 4
  • 10