Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary Operator in Razor View of MVC3 and Checked Attribute

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 checkboxs checked, how can I use ternary operator and handle checked attribute correctly?

like image 802
Saeid Avatar asked Dec 06 '22 14:12

Saeid


1 Answers

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/

like image 133
Chris Avatar answered Jan 16 '23 15:01

Chris