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?
If a radio button is checked, its checked property is true .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With