动态创建里面UpdatePanel控件? [英] Dynamic created controls inside UpdatePanel?

查看:105
本文介绍了动态创建里面UpdatePanel控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建控件,这将允许用户设计自己的网站结构。我想象着里面的的UpdatePanel 文本框(换页名)和控制(S)按钮'下面添加。它会是这样的:

I want to create control that will allow user to design his own website structure. I imagined that inside UpdatePanel is control(s) with TextBox ( for page name) and Button 'add below'. It would looks like:

|   "Questions" |
| [ add below ] |

|     "Tags"    |
| [ add below ] |

|    "Badges"   |
| [ add below ] |

现在,当标签元素上的按钮,用户点击,应该出现新的标签和徽章之间,可编辑的名称,以便用户可以将其命名为用户为例。它应该不完全回发(避免页面闪烁)来完成。

now when user click on button in "Tags" element there should appear new one, between "Tags" and "Badges", with editable name, so user can name it "Users" for example. It should be done without full postback ( to avoid page blinks).

现在是我的问题:因为他们不存在,我无法加载这些控件(最后不是全部)在OnInit的,但我必须照顾他们的单击事件,所以我应该附加事件侦听器,我应该在初始化阶段完成。 我怎样才能实现上述功能?

Now is my problem: I cannot load those controls (at last not all of them) in onInit since they dont exist, but I have to attend to theirs click event so I should attaching event listener what should be done during Init phase. How can I achieve described functionality?

我打它周围太多时间,我很困惑。我将是任何提示感谢。

I played around it for too much time and I am confused. I would be grateful for any tips.

推荐答案

这是一个棘手的情况,因为你是在处理动态控件需要填充它们在页面初始化,以坚持视图状态,也为内部的添加控件的事件在按钮点击更新面板不似乎得到注册,直到下一次回传,所以正常按钮单击事件只有每一次你点击一个新添加的控件激发。可能有一些其他的方式来解决这个比我的方式。如果有人知道我想了解一下。

This is a tricky situation because you are dealing with dynamic controls you need to populate them on page init in order to persist viewstate, also events for controls added inside an update panel during button clicks do not seems to get registered until the next postback, so the normal button click event only fires once every other time you click on a newly added control. There may be some other way to work around this than the way I did it. If anyone knows I would like find out.

我的解决办法是让你有动态添加什么样的清单,并将其存储在一个会话变量(因为页面初始化过程中未加载视图状态)。然后在页面上初始化加载你previously添加任何控件。然后用一些自定义code代替或正常的单击事件的页面加载过程中处理click事件。

My solution is to keep a list of what you have added dynamically, and store it in a session variable (because the viewstate is not loaded during page init). Then on the page init load any controls you have previously added. Then handle the click event during the page load with some custom code instead or the normal click event.

我创建了一个示例页面,以帮助测试。

I have created a sample page to help test this.

下面是code的aspx页面(Default.aspx的):

Here is the code for the aspx page (default.aspx):

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <p>This only updates on full postbacks: <%= DateTime.Now.ToLongTimeString() %></p>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:PlaceHolder ID="PlaceholderControls" runat="server"></asp:PlaceHolder>
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>

这是隐藏页(default.aspx.cs)在code中的code:

And here is the code for the code behind page (default.aspx.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    /// <summary>
    /// this is a list for storing the id's of dynamic controls
    /// I have to put this in the session because the viewstate is not
    /// loaded in the page init where we need to use it
    /// </summary>
    public List<string> DynamicControls
    {
        get
        {
            return (List<string>)Session["DynamicControls"];
        }
        set
        {
            Session["DynamicControls"] = value;
        }
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        PlaceholderControls.Controls.Clear();

        //add one button to top that will cause a full postback to test persisting values--
        Button btnFullPostback = new Button();
        btnFullPostback.Text = "Cause Full Postback";
        btnFullPostback.ID = "btnFullPostback";
        PlaceholderControls.Controls.Add(btnFullPostback);

        PlaceholderControls.Controls.Add(new LiteralControl("<br />"));

        PostBackTrigger FullPostbackTrigger = new PostBackTrigger();
        FullPostbackTrigger.ControlID = btnFullPostback.ID;

        UpdatePanel1.Triggers.Add(FullPostbackTrigger);
        //-----------------------------------------------------------------------




        if (!IsPostBack)
        {
            //add the very first control           
            DynamicControls = new List<string>();

            //the DynamicControls list will persist because it is in the session
            //the viewstate is not loaded yet
            DynamicControls.Add(AddControls(NextControl));

        }
        else
        {
            //we have to reload all the previously loaded controls so they
            //will have been added to the page before the viewstate loads
            //so their values will be persisted
            for (int i = 0; i < DynamicControls.Count; i++)
            {
                AddControls(i);
            }
        }


    }

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            //we have to increment the initial
            //control count here here be cause we cannot persit data in the viewstate during 
            //page init

            NextControl++;

        }
        else
        {
            HandleAddNextClick();           

        }

    }

    /// <summary>
    /// this function looks to see if the control which caused the postback was one of our 
    /// dynamically added buttons, we have to do this because the update panel seems to interefere
    /// with the event handler registration.
    /// </summary>
    private void HandleAddNextClick()
    {
        //did any of our dynamic controls cause the postback if so then handle the event
        if (Request.Form.AllKeys.Any(key => DynamicControls.Contains(key)))
        {
            DynamicControls.Add(AddControls(NextControl));
            NextControl++;
        }
    }



    protected void btnAddNext_Command(object sender, CommandEventArgs e)
    {
        //this is intentionally left blank we are handling the click in the page load
        //because the event for controls added dynamically in the click does
        //not get registered until after a postback, so we have to handle it 
        //manually.  I think this has something to do with the update panel, as it works 
        //when not using an update panel, there may be some other workaround I am not aware of

    }

    /// <summary>
    /// variable for holding the number of the next control to be added
    /// </summary>
    public int NextControl
    {
        get
        {
            return  ViewState["NextControl"] == null ? 0 : (int)ViewState["NextControl"];
        }
        set
        {
            ViewState["NextControl"] = value;
        }
    }


    /// <summary>
    /// this function dynamically adds a text box, and a button to the placeholder
    /// it returns the UniqueID of the button, which is later used to find out if the button
    /// triggered a postback
    /// </summary>
    /// <param name="ControlNumber"></param>
    /// <returns></returns>
    private string AddControls(int ControlNumber)
    {
        //add textbox
        TextBox txtValue = new TextBox();
        txtValue.ID = "txtValue" + ControlNumber;
        PlaceholderControls.Controls.Add(txtValue);

        //add button
        Button btnAddNext = new Button();
        btnAddNext.Text = "Add Control " + ControlNumber;
        btnAddNext.ID = "btnAddNext" + ControlNumber;
        int NextControl = ControlNumber + 1;
        btnAddNext.CommandArgument = NextControl.ToString();

        btnAddNext.Command += new CommandEventHandler(btnAddNext_Command);
        PlaceholderControls.Controls.Add(btnAddNext);

        //add a line break
        PlaceholderControls.Controls.Add(new LiteralControl("<br />"));

        return btnAddNext.UniqueID;

    }    
}

让我知道,如果这个code可以帮助你出去的。我试图用我的东西是怎么回事,它是如何工作的理解添加注释。

Let me know if this code helps you out at all. I tried to add comments with my understanding of what is going on and how it works.

这篇关于动态创建里面UpdatePanel控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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