Razor html helper parameter shows message about redundant conditional ternary expression usage

262 Views Asked by At

Why there is a Visual Studio message about redundant conditional ternary expression usage, when there is a mouse over expression (also expression "true : false" has lower opacity). Does it tell me about i can write somehow less code to get what i want (if ViewBag.CMSClientStatus is equal to "Действующий", then check the radio)?

@Html.RadioButton("ClientStatus", "Real",  ViewBag.CMSClientStatus == "Действующий" ? true : false, new { @readonly = true })

Screenshot

3

There are 3 best solutions below

1
On

Instead of:

ViewBag.CMSClientStatus == "Действующий" ? true : false

Just use:

ViewBag.CMSClientStatus == "Действующий"

The equality operator (==) already returns true or false, so no need for a conditional operator.

0
On

Expression ViewBag.CMSClientStatus == "Действующий" already returns true or false. Ternary operator adds nothing to your logic, it's redundant as Visual Studio suggest.

0
On

I've write as it was suggested in previous two answers. But then an error came out: "Extension methods cannot be dynamically dispatched".

Screenshot

Answer was found here. I need cast the dynamic type to Boolean type. My final entry is:

@Html.RadioButton("ClientStatus", "Потенциальный",  (bool) (ViewBag.CMSClientStatus == "Потенциальный"), new { @readonly = true })