Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a radio button based upon the enum value

Tags:

asp.net-mvc

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?

like image 274
learning Avatar asked Apr 19 '10 06:04

learning


People also ask

Does radio button have checked value?

If a radio button is checked, its checked property is true .

How do I select a radio button when a label is clicked?

We can do this by providing the radio's ID attribute value in the for attribute of the <label> element. Now, you can click the associated label to select the corresponding radio button. If your radio button doesn't have an id attribute, you can wrap the radio button directly inside the <label> element.


1 Answers

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.

like image 130
Prutswonder Avatar answered Oct 10 '22 20:10

Prutswonder