日志标签:RadioButton

ASP.NET MVC 2.0 如何使用Html.RadioButtonFor?

时间:2010年07月03日作者:Winson查看次数:查阅:2,354评论次数:0

MVC 2.0里支持强类型实体绑定,可以直接使用如

1
<%: Html.TextBoxFor(model => model.Description, new { @class="text"})%>

来自动将实体绑定到表单里,但我不知道如何使用 Html.RadioButtonFor 来生成 RadioButton ? 在使用 Html.RadioButtonFor 必须至少2个参数,另一个是指一个object,我绑定的字段是一个bool型的,如何能自动生成相关的RadioButton 呢?

开始时一直觉得一句话就可以完成,弄了半天也没成功,后来想起了其实调用一次 Html.RadioButtonFor 就只生成一个 RadioButton,那又怎么可能一句就生成2个button呢?呵,傻了吧,唉,其实只要分别调用2次就可以了啊,然后再加上个 if 判断一下当前值即可,以下是实现的代码:

1
2
3
4
5
6
7
8
9
10
11
<%if(Model.OffStatus){ %>
    <%: Html.RadioButtonFor(model => model.OffStatus, true, new { @id = "radio1", @name = "Status", @checked="checked" })%>              
    <label for="radio1">开启</label>
    <%: Html.RadioButtonFor(model => model.OffStatus, false, new { @id = "radio2", @name = "Status" })%>
    <label for="radio2">关闭</label>
    <%}else { %>
    <%: Html.RadioButtonFor(model => model.OffStatus, true, new { @id = "radio1", @name = "Status" })%>              
    <label for="radio1">开启</label>
    <%: Html.RadioButtonFor(model => model.OffStatus, false, new { @id = "radio2", @name = "Status", @checked = "checked" })%>
    <label for="radio2">关闭</label>
<%} %>

就这么简单……. :smile:

无觅相关文章插件,快速提升流量