Search code examples
asp.netrazoranonymous-typesternary

ASP.NET razor ternary expression on anonymous types


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?


Solution

  • 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" })