Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 233
user1408767 Avatar asked Dec 19 '22 12:12

user1408767


1 Answers

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" })
like image 66
p.s.w.g Avatar answered Dec 28 '22 09:12

p.s.w.g