加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何根据枚举值检查单选按钮

发布时间:2020-12-16 03:41:00 所属栏目:asp.Net 来源:网络整理
导读:我有一个枚举.根据模型带来的价值,我必须检查单选按钮.我怎样才能做到这一点? %=Html.RadioButton("Role",Role.Viewer)%%= .Role.Viewer% %=Html.RadioButton("Role",.Role.Reporter)%%= Role.Reporter% %=Html.RadioButton("Role",Role.User)%%= Role.User
我有一个枚举.根据模型带来的价值,我必须检查单选按钮.我怎样才能做到这一点?

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

我的枚举将是数字1到3,例如如果选择的枚举值为1,如何检查Role.Viewer?

解决方法

您可以将枚举值强制转换为int而不会出现任何问题:

<%=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%>

请记住,枚举定义隐式具有从0开始的索引.如果您想要更多控制,可以自己手动将int值分配给枚举:

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

[更新]

根据您的评论,我得到您想要将数据库值绑定到radiolist.您可以使用以下代码执行此操作:

<%=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%>

此代码假定数据库值与Model.Role同步,但您可以将其替换为您自己的逻辑.并且有more elegant ways写了radiobutton枚举,但只有3个无线电选项,坚持这个解决方案是安全的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读