Ternary Operator in Razor View of MVC3 and Checked Attribute

asp.net-mvc, asp.net-mvc-3, checked, razor, ternary-operator

Solution

Unfortunately, in razor V1, you must do it this way:

<input type="checkbox" value="@item.Id" @(item.HasAccess ? "checked=\"checked\"" : "") />

This is because in the HTML world, the mere presence of the attribute at all, regardless of the value, tells the browser to check the box.

In Razor V2, this will be less of a problem. See the conditional attributes section of the article below:

http://vibrantcode.com/blog/2012/4/10/whats-new-in-razor-v2.html/

Problem

I use this: ``` <input type="checkbox" value="@item.Id" checked="@(item.HasAccess ? "checked" : "")"/> ``` This worked correctly: I mean when `HasAccess` is `true` then `checked="checked"` and when `HasAccess` is `false` then `checked=""` but always the `checkbox`s checked, how can I use ternary operator and handle `checked` attribute correctly?

Original source