views:

125

answers:

2

Hello All,

I have what should be an easy question for you today.

I have two radio buttons in my view:

Sex:
<%=Html.RadioButton("Sex", "Male", true)%> Male
<%=Html.RadioButton("Sex", "Female", true)%> Female

I need to select one based on the value returned from my database. The way I am trying to do it now is:

ViewData["Sex"] = data.Sex; //Set radio button

But that is not working. I have tried every possible combination of isChecked properties. I know that data.Sex is returning either "Male" or "Female". What do I need to do to check the appropriate radio button?

A: 

Remove the third parameter from the helper:

<%= Html.RadioButton("Sex", "Male") %> Male 
<%= Html.RadioButton("Sex", "Female") %> Female

And in your controller action:

ViewData["Sex"] = "Female";

Will check the second radio.

Darin Dimitrov
Thank you sir! I knew it was something easy like that.
Jacob Huggart
@Jacob, if you consider that this answer was helpful to you, accept it by clicking on the green tick next to it. This will improve your accept rate which currently is 0 out of 6 questions which is not good for your reputation.
Darin Dimitrov
A: 

Not sure about what you are storing in the view data, but you could do something like:

<%=Html.RadioButton("Sex", "Male", ViewData["Sex"] == "Male")%> Male
<%=Html.RadioButton("Sex", "Female", ViewData["Sex"] == "Female")%> Female

Which places a boolean in the 'Checked' overload of the RadioButton method if your view data contains the specified string.

Andrew