如何将窗格的可见性与另一个控件绑定?

时间:2010-01-16 20:14:31

标签: asp.net asp.net-ajax

所以我有两个单选按钮。如果选择RadioButton1,我希望Panel1可见,Panel2隐藏。如果选择了RadioButton2,我希望Panel2可见,并且要隐藏Panel1。有没有办法在不需要回发的情况下执行此操作?

2 个答案:

答案 0 :(得分:1)

你可以用一点点javascript做到这一点。为两个单选按钮添加一个onclick处理程序并调用一个函数来更新视图:

<input type="radio" id="radio_1" onclick="updateView">Radio 1
<input type="radio" id="radio_2" onclick="updateView">Radio 2

<script>
  function updateView() {
    var radio_1 = document.getElementById("radio_1");
    // etc... get radio 2 and panels the same way
    panel_1.style.display = radio_1.checked ? "block" : "none";
    panel_2.style.display = radio_2.checked ? "block" : "none";
  }
</script>

答案 1 :(得分:1)

基本上有两种方法可以做到这一点:完全是客户端和服务器端,具有异步回发。

<强>客户端:

CSS:

.hidden { display: none; }

使用Javascript:

toggleDiv = function(id, opt) {
    _id = document.getelementbyid(id);
    if (opt == "show") {
        _id.style.display = "block";
    } else {
        _id.style.display = "hidden";
    }

}

ASPX:

<asp:radiobutton id="rbOne" runat="server" />
<asp:radiobutton id="rbTwo" runat="server" />

<div id="panel1" class="hidden">
    <p>Panel 1</p>
</div>

<div id="panel2" class="hidden">
    <p>Panel 2</p>
</div>

代码隐藏:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    ' Apply onclick handlers to the radio buttons
    If Not Page.IsPostBack Then
        rbOne.Attributes.Add("onclick", "toggleDiv('" & rbOne.ClientId() & "', 'show'); toggleDiv('" & rbTwo.ClientId & "', 'hide');")
        rbTwo.Attributes.Add("onclick", "toggleDiv('" & rbOne.ClientId() & "', 'hide'); toggleDiv('" & rbTwo.ClientId & "', 'show');")
    End If

End Sub

服务器端

ASPX:

<asp:UpdatePanel id="upRadioButtons" runat="server">
    <asp:radiobutton id="rbOne" runat="server" autopostback="true" />
    <asp:radiobutton id="rbTwo" runat="server" autopostback="true" />

    <asp:multipage id="mvButtonPanels" runat="server">
        <asp:view id="view1" runat="server">
            <p>Panel 1</p>
        </asp:view>
        <asp:view id="view2" runat="server">
            <p>Panel 2</p>
        </asp:view>
    </asp:multipage>
</asp:UpdatePanel>

代码隐藏:

Protected Sub rbOne_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rbOne.CheckedChanged
    mvButtonPanels.ActiveViewIndex = 0
End Sub

Protected Sub rbTwo_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rbTwo.CheckedChanged
    mvButtonPanels.ActiveViewIndex = 1
End Sub

还有很多其他方法可以做到这一点,例如在客户端使用jQuery,在服务器端使用少一点硬编码的逻辑。