Reputation: 18660
Hi I have some code like:
foreach (var item in Model) {
<div>
@Html.DisplayFor(modelItem => item.UserRole.Role.Name)
</div>
<div>
<input type="checkbox" name="ids" checked="@item.Active" />
</div>
}
What I was trying to achieve was set the checkbox check if item is Active else not checked.
I understand the syntax should be checked="checked"
and I've set it up as checked="true"
I don't understand how to convert the true to checked and what to do for false.
I was trying to use a ternary but it wouldn't play nice. Can anybody help?
Upvotes: 1
Views: 2330
Reputation: 13682
The presence of the checked attribute will cause it to be checked, i.e It doesn't matter (AFAIK) what the value of the attribute is. So you need to detect whether or not to add the checked attribute at all:
foreach (var item in Model)
{
<div>
@Html.DisplayFor(modelItem => item.UserRole.Role.Name)
</div>
<div>
<input type="checkbox" name="ids" @if (item.Active) { Write("checked"); }/>
</div>
}
Edited: changed to MДΓΓ БДLL version, much cleaner.
One brute force approach =P
Upvotes: 2
Reputation: 1198
In HTML, to uncheck it, just remove the checked="whatever" attribute. Technically, HTML doesn't care what the value of checked="" is, just that it exists and that it's valid markup.
Upvotes: 1
Reputation: 944545
I understand the syntax should be
checked="checked"
If you are using XHTML, that is true. In HTML the shorthand syntax is recommended where you specify only the value of that attribute (although user agents don't have a problem with the long for these days, it is quicker to type).
<input type="checkbox" name="foo" value="bar" checked>
I don't understand how to convert the true to checked
That depends on the (unspecified) template language you are using.
and what to do for false.
Don't include the checked attribute at all.
<input type="checkbox" name="foo" value="bar">
Upvotes: 1