views:

143

answers:

2

In my controller I am setting my value to true:

ViewData[itemName] = true;

Then in my view I am trying to set the item with true as select radio button. I have tried the following:

    <%= Html.RadioButton("default",item.Name,
             ((bool)ViewData[item.Name])==null ? false:true) %> 

    <%= Html.RadioButton("default",item.Name,
             ViewData[item.Name]) %> 

    <%= Html.RadioButton("default",item.Name,
             ViewData["defaultItem"]==item.Name) %> 
    //In the case above I assigned ViewData["defaultItem"] = itemName;

any ideas?

A: 

In your second RadioButton, you're not actually specifying a boolean condition for "IsChecked."

It should look something like this:

    <%= Html.RadioButton("default",item.Name,
             ViewData[item.Name] == "something") %>
Robert Harvey
I tried that on the third section of the code above and it did not worked. I thought it was going to, though. Thanks.
Geo
+1  A: 

I haven't looked in to this particular problem at all, but thought I would lend a hand in compacting the code a bit.

To make the follow a bit less verbose:

        <% if (ViewData[item.Name] == null)
           { %>
            <%= Html.RadioButton("defaultNAME", item.Name)%>
        <% }
           else
           {%>
           <%= Html.RadioButton("defaultNAME", item.Name, 
                                    (bool)ViewData[item.Name])%> 
        <% } %>

You can do this:

<%= ViewData[item.Name] == null ? Html.RadioButton("defaultNAME", item.Name) : Html.RadioButton("defaultNAME", item.Name, (bool)ViewData[item.Name]) %>

I know this doesn't help your question any, but since this is fairly straightforeward code, I think this is a good candidate for squeezing these eight or nine lines down into one.

Good luck!

EDIT:

I realized after submitting that this can be made shorter still. Only one call to Html.RadioButton() is necessary.

<% bool defaultValue = false; %>
<%= Html.RadioButton("defaultNAME", item.Name, (bool) (ViewData[item.Name] ?? defaultValue)) %>

Using the null coalescing operator, we can just grab some default value if ViewData[item.Name] is null. Feel free to hardcode your default value instead of specifying it in a variable. I did that just to make the example clearer. All three code blocks are semantically equivalent (although should produce fairly different IL, considering that the first block drops in and out of ASP markup).

JoshJordan
Exactly what I was looking. Thanks Josh!!!
Geo