动态添加控件在ASP.NET AJAX一个UpdatePanel [英] Adding controls dynamically to an UpdatePanel in ASP.NET AJAX

查看:152
本文介绍了动态添加控件在ASP.NET AJAX一个UpdatePanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几点很简单code

I have the following really simple code

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
    <asp:PlaceHolder ID="PlaceHolder1" runat="server">
    </asp:PlaceHolder>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>

而codebehind

And the codebehind

protected void Button1_Click(object sender, EventArgs e)
{
    Literal literal = new Literal();
    literal.Text = DateTime.Now.ToString();
    literal.ID = DateTime.Now.Ticks.ToString();

    // These both work fine the first time the button is clicked
    // but the second time nothing is added.
    UpdatePanel1.ContentTemplateContainer.Controls.Add(literal);
    PlaceHolder1.Controls.Add(literal);
}

我的问题就来了,该文字控制功能只添加一次。我已经冲刷谷歌和博客网站(加上书籍),但没有任何运气。我在想什么?

My problem comes in that the Literal control is only ever added once. I've scoured google and blog sites (plus books) but without any luck. What am I missing?

推荐答案

在asp.net,会自动在每次回发所产生的ASPX文件控制。您所创建的控件不在ASPX code所以框架不会为您创建它们。当您第一次执行Button1_Click的方法,你添加一个额外的控制页面。第二次执行Button1_Click的方法,你在另一个帖子回和第一个加按钮已被遗忘。所以这回发的结果就是你再另外一个按键即可获得。

In asp.net, the controls in the ASPX file are automatically generated on each postback. The controls you've created are not in the ASPX code so the framework does not create them for you. The first time you execute the Button1_Click method, you add one extra control to the page. The second time you execute the Button1_Click method, you're on another post back and that first extra button has been forgotten about. So the result of that postback is you get one extra button again.

这将在每次创建一个额外的控制你单击按钮(虽然时间戳将更新每次preSS因为正在重新创建的控制按钮)

This will create one extra control each time you click the button (although the timestamps will update each time you press the button because the controls are being re-created)

protected void Button1_Click(object sender, EventArgs e)
{
    int count = 0;

    if (ViewState["ButtonCount"] != null)
    {
        count = (int)ViewState["ButtonCount"];
    }

    count++;
    ViewState["ButtonCount"] = count;

    for (int i = 0; i < count; i++)
    {
        Literal literal = new Literal();
        literal.Text = DateTime.Now.ToString();
        literal.ID = DateTime.Now.Ticks.ToString();

        UpdatePanel1.ContentTemplateContainer.Controls.Add(literal);
        PlaceHolder1.Controls.Add(literal);
    }            
}

这篇关于动态添加控件在ASP.NET AJAX一个UpdatePanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆