开发者

How to check a radio button based upon the enum value

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜