【问题标题】:Conditionally show/hide html area in ASP.NET有条件地显示/隐藏 ASP.NET 中的 html 区域
【发布时间】:2013-12-18 20:34:37
【问题描述】:

我需要使用 C# 显示和隐藏 ASP.NET 页面的不同区域。 当用户单击第一个单选按钮时,我希望我的 ASP.NET html 显示第一段并隐藏第二段,当用户单击第二个单选按钮时,我希望我的 ASP.NET html 显示第二段。

这是我的 html 代码。


<form id="form1" runat="server">
<div>

    <br />
    <asp:RadioButtonList ID="RadioButtonList1" runat="server">
        <asp:ListItem Value="P1">Show First Paragraph</asp:ListItem>
        <asp:ListItem Value="P2">Show Second Paragraph</asp:ListItem>
    </asp:RadioButtonList>


    <br />
    This is my 1st Paragraph.<br />
    <br />


    <br />
    This is my 2nd Paragraph.<br />
    <br />        

</div>
</form>

因此,当用户单击标有“显示第一段”的第一个单选按钮时,我希望我的页面显示带有文本“这是我的第 1 段”的第一段。并用文本“这是我的第二段”隐藏第二段,反之亦然。

谁能告诉我正确的 C# 事件代码来完成这个?

【问题讨论】:

  • 我用你的标题在谷歌上搜索,发现几篇文章可以满足你的要求。到目前为止,您做了什么?失败的原因是什么?
  • 做这个服务器端而不是客户端有什么特殊原因吗?
  • 我一直认为在服务器端编码更好,因为一些访问者可以在他们的浏览器上关闭 javascript,而且我不会有很多访问者访问我的网站,所以我不担心网络服务器负载。我可能错了,但这是我从一些计算机书籍中读到的。

标签: c# asp.net events conditional


【解决方案1】:

首先添加一个 OnSelectedIndexChanged 事件并将其设置为 AutoPostBack,以便当您选择单选按钮时,它会回发到服务器。然后将您的段落放在面板或文字中。

ASP.NET:

<asp:RadioButtonList ID="RadioButtonList1" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged" AutoPostBack="true" runat="server">
    <asp:ListItem Value="P1">Show First Paragraph</asp:ListItem>
    <asp:ListItem Value="P2">Show Second Paragraph</asp:ListItem>
</asp:RadioButtonList>

<br />
<asp:Panel ID="Panel1" Visible="false" runat="server">
This is my 1st Paragraph.<br />
</asp:Panel>


<asp:Panel ID="Panel2" Visible="false" runat="server">
This is my 2nd Paragraph.<br />
</asp:Panel>

然后在您的代码中,您编写名为的事件:

protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Panel1.Visible = Panel2.Visible = false;
    if (RadioButtonList1.SelectedValue == "P1")
        Panel1.Visible = true;
    else if (RadioButtonList1.SelectedValue == "P2")
        Panel2.Visible = true;
}

【讨论】:

  • 非常感谢,我什至对面板一无所知。
  • 我不知道如何将此问题标记为已回答,但我刚刚发现...大声笑
猜你喜欢
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
  • 2022-08-11
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-19
相关资源
最近更新 更多