tags:

views:

207

answers:

1

I have an enum. Based upon the value brought by model, I have to check radio button. How can I do that?

<%=Html.RadioButton("Role", Role.Viewer)%><%= .Role.Viewer%>
        <%=Html.RadioButton("Role",.Role.Reporter)%><%= Role.Reporter%>
        <%=Html.RadioButton("Role",Role.User)%><%= Role.User%>

My enum would be having the numbers 1 to 3 for e.g. How can I check the Role.Viewer if enum value selected is 1?

+4  A: 

You can cast the enum values to int without any problems:

<%=Html.RadioButton("Role", (int)Role.Viewer)%><%= (int)Role.Viewer%>
<%=Html.RadioButton("Role", (int)Role.Reporter)%><%= (int)Role.Reporter%>
<%=Html.RadioButton("Role", (int)Role.User)%><%= (int)Role.User%>

Bear in mind that the enum definition implicitly has a 0-based index. If you want more control, you can manually assign int values to the enum yourself:

public enum Role {
    Viewer = 1,
    Reporter = 2,
    User = 3
}

[Update]

Based on your comments, I get that you want to bind a database value to the radiolist. You can do that by using the following code:

<%=Html.RadioButton("Role", (int)Role.Viewer, Model.Role == Role.Viewer)%><%= (int)Role.Viewer%>
<%=Html.RadioButton("Role", (int)Role.Reporter, Model.Role == Role.Reporter)%><%= (int)Role.Reporter%>
<%=Html.RadioButton("Role", (int)Role.User, Model.Role == Role.User)%><%= (int)Role.User%>

This code assumes the database value is synced with Model.Role, but you can replace it with your own logic of course. And there are more elegant ways to write the radiobutton enumeration, but for only 3 radio options, it's safe to stick to this solution.

Prutswonder
That`s helpful, how do I check button based on the value return. eg, let`s say 1 has been returned, I will need to select the Role.Viewer radio button and the others remained unchanged?
You can do that by casting the int value back to the enum: `var myRole = (Role)returnValue;`.
Prutswonder
I think you haven`t understood my question. I retrieve the values from my database, and from that I find Role selected is number 3. I need to check the radio button for Role.User. If other numbers return, their corresponding buttons have to be checked, upon loading.
Updated my answer for you with a sample for that.
Prutswonder
it`s not working , the radio button isn`t being checked accordingly!
Actually the code you provided is working but only one radio button selected!
How can we use Html.|radiobuttonfor in this case?
A `RadioButtonList` is for a single selection only. If you want multiple selected items, then you should use a `CheckboxList` and not a `RadioButtonList`. Don't know if it's been added in MVC2, but you could add it yourself. See this link how to do this: http://blogs.msdn.com/miah/archive/2008/11/10/checkboxlist-helper-for-mvc.aspx
Prutswonder