5

I have the following code:

<div class="col-sm-8 col-sm-pad ">
      @Html.DropDownListFor(model => model.SelectedAssignToId, Model.AssignToListItems,
      ViewBag.CanEditRequest ? new { @class = "form-control" } : new { @class = "form-control", @disabled = "disabled" })
</div>

But I receive the following error:

error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'AnonymousType#1' and 'AnonymousType#2'

How can use a ternary expression on anonymous types in razor?

user1408767
  • 677
  • 1
  • 8
  • 30

1 Answers1

12

You can cast one side of the ternary expression to an object:

@Html.DropDownListFor(model => model.SelectedAssignToId, Model.AssignToListItems,
ViewBag.CanEditRequest ? (object)new { @class = "form-control" } : new { @class = "form-control", @disabled = "disabled" })

Or perhaps try moving the ternary expression into the anonymous type, like this:

@Html.DropDownListFor(model => model.SelectedAssignToId, Model.AssignToListItems,
new { @class = "form-control", @disabled = ViewBag.CanEditRequest ? null : "disabled" })
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • 1
    I did try it this way : @disabled = ViewBag.CanEditRequest ? null : "disabled", but when CanEditRequest was true it still rendered disabled="" in the select element. – user1408767 Aug 07 '14 at 12:51