不需要PostBack即可更改标签文本(使用更新面板)

7

我创建了一个ASP.NET网站。我的目的是根据下拉列表中选择的项目使标签内容发生更改。我尝试了以下方法,但未成功:

下拉列表如下:

<asp:DropDownList ID="DropDown1" runat="server" >
    <asp:ListItem Value="a"></asp:ListItem>
    <asp:ListItem Value="b"></asp:ListItem>
    onselectedindexchanged="DropDown1_SelectedIndexChanged"
</asp:DropDownList>

标签:
<asp:Label ID="Label1" Text="" runat="server"/>

我希望不必使用PostBack来完成这个操作。

我尝试使用ajax Update Panel 来实现:

<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">        
    <Triggers>
        <asp:AsyncPostBackTrigger controlid="DropDown1"                                       EventName="SelectedIndexChanged" />
    </Triggers>
    <ContentTemplate>
        <asp:Label ID="Label1" Text="" runat="server"/>
    </ContentTemplate>
</asp:UpdatePanel>

在代码后台的DropDown1_SelectedIndexChanged事件中:

protected void DropDown1_SelectedIndexChanged(object sender, EventArgs e)
{
    Label1.Text = DropDown1.SelectedValue;
}

但这不起作用。

有人可以帮我解决吗?

非常感谢任何帮助。

3个回答

9

以下是您的解决方案:

将下拉列表aspx控件替换为以下控件:

  <asp:DropDownList ID="DropDown1" runat="server" onselectedindexchanged="DropDown1_SelectedIndexChanged" AutoPostBack="true">
                <asp:ListItem Value="a"></asp:ListItem>
                <asp:ListItem Value="b"></asp:ListItem>
           </asp:DropDownList>

<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
    <ContentTemplate>
        <asp:Label ID="Label1" Text="test" runat="server"/>
    </ContentTemplate>

    <Triggers>
        <asp:AsyncPostBackTrigger controlid="DropDown1" EventName="SelectedIndexChanged" />
    </Triggers>
</asp:UpdatePanel>

请检查这段代码...只需在aspx页面中替换您的代码。您的代码后台是正确的... - sikender
所以,即使只有UpdatePanel中的内容被重新渲染,整个页面数据仍会在部分回发时发送到服务器? - Răzvan Flavius Panda
是的,页面加载方法再次被调用了。但是我们会在那里加上if(!Page.ispostback)方法。 - sikender
非常感谢。我不知道AutoPostBack="true"会执行完整的后台提交。但显然并不是这样。 - Y2theZ

5

您需要启用自动提交并将事件处理程序定义放在正确的位置:

<asp:DropDownList ID="DropDown1" runat="server" onselectedindexchanged="DropDown1_SelectedIndexChanged" AutoPostBack="true">
                                <asp:ListItem Value="a"></asp:ListItem>
                                <asp:ListItem Value="b"></asp:ListItem>
                            </asp:DropDownList>

谢谢你的回答,它起作用了。不幸的是,我不能接受两个答案。 - Y2theZ

0

这很有趣。但其他解决方案涉及使用JavaScript(我从未使用过),我可能会在有空时间时去了解一下。 - Y2theZ
3
该链接网站似乎已被黑客攻击。 - epelc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接