views:

46

answers:

1

I have a Table containing some information that I need. All these rows also contains a column with a radio button in it so that the user is suppose to be able to check one of the rows as default.

When I'm bringing the data back from the DB and want to select the one that's currentlly the default one.

<% foreach (var item in (IEnumerable<Locale>) ViewData["Locales"]) { %>
    <tr>
        <td>
            <%= Html.Encode(item.Language.Name) %>
        </td>
        <td>
            <input type="radio" id="defaultLocale" name="defaultLocele" value="on" checked="<%= item.Default == false ? "false" : "true" %>" />
        </td>

I've also tried to do this:

<input type="radio" id="defaultLocale" name="defaultLocele" value="on" checked="<%=item.Default == false ? "" : "checked" %>" />

but nothing seems to do the right thing. I always end up with having the last row in checked, which it isn't for sure.

+1  A: 

In html checked is no bool value of true or false. You have to set checked="checked" in order to have the checkbox checked (If you want correct syntax). But most browsers accept any checked="..." as setting. So your checked="false" gets interpreted as "Is checked". So all your checkboxes are interpreted as checked and becouse only one can be, the last one is checked.

If you dont want it to be checked, you have to remove the whole checked= attribute.

<input type="radio" id="defaultLocale" name="defaultLocele" value="on" <%=item.Default ? "" : "checked=\"checked\"" %> />
Marks
Yes. And that's what I'm doing on the second piece of code there. Or am I doing that wrong as well? I really thought this would be a piece of cake, but I'm starting to go mad on this now.
MrW
His statement already does that. @MrW - try putting single quotes inside the `checked` value, like this: `checked="<%=item.Default == false ? '' : 'checked' %>"`
Matt Ball
Also, since you're already testing against a boolean value, there's really no need to compare it to `false`: `checked="<%=item.Default ? 'checked' : '' %>"`
Matt Ball
See my edited answer, you have to remove the whole attribute.
Marks
I did this, "<%= Html.Encode(item.Default ? "checked=\"'checked'\"" : "") %>". I needed the Html.Encode as otherwise a custom attributed was there instead as well if it was not checked - something like this ??="". Thanks for all quick and great help!!!
MrW