在ASP.Net持续动态控制 [英] Persistent dynamic control in ASP.Net

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

问题描述

<asp:Button onclick="Some_event" Text="Add TextBox" ID="id1" runat="server" />
//once clicked:
<asp:TextBox ID="txt1" ......></asp:TextBox>
//when clicked again:
<asp:TextBox ID="txt1" ......></asp:TextBox>
<asp:TextBox ID="txt2" ......></asp:TextBox>
//and so on...

有没有一种方法来创建动态控件甚至回传之后,将继续存在?换句话说,当用户点击该按钮时,将产生一个新的文本框,当点击再次第一个将保持而第二个将生成。我怎样才能做到这一点使用asp.net?我知道,如果我能在page_init事件创建控件然后他们将持续存在,但page_init发生之前,我不知道这是否可以处理一个按钮的点击,因此必须有另一种方式。

Is there a way to create dynamic controls which will persist even after the postback? In other words, when the user clicks on the button, a new textbox will be generated and when clicks again the first one will remain while a second one will be generated. How can I do this using asp.net ? I know that if I can create the controls in the page_init event then they will persist but I dont know if it possible to handle a button click before the page_init occurs, therefore there must be another way.

推荐答案

是的,这是可能的。要做到这一点使用ASP.NET纯粹(这似乎是你问什么)将是保持文本框的计数的一种方式控制已添加(存储在 ViewState的那个值),并重新创建文本框控制在的Page_Load 事件。当然,现如今大多数人可能会使用Javascript或jQuery来处理这个任务的客户端,但我把一个简单的例子来演示它的工作原理与回送:

Yes, this is possible. One way to do this using purely ASP.NET (which seems like what you're asking for) would be to keep a count of the TextBox controls that you have added (storing that value in the ViewState) and recreate the TextBox controls in the Page_Load event. Of course, nowadays most people would probably use Javascript or jQuery to handle this task client side, but I put together a quick example to demonstrate how it works with postbacks:

头版:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicControls.aspx.cs" Inherits="MyAspnetApp.DynamicControls" EnableViewState="true" %>
<!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 runat="server"></head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnAddTextBox" runat="server" Text="Add" OnClick="btnAddTextBox_Click" />
        <asp:Button ID="btnWriteValues" runat="server" Text="Write" OnClick="btnWriteValues_Click" />
        <asp:PlaceHolder ID="phControls" runat="server" />
    </div>
    </form>
</body>
</html>

背后code:

using System;
using System.Web.UI.WebControls;

namespace MyAspnetApp
{
    public partial class DynamicControls : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Recreate textbox controls
            if(Page.IsPostBack)
            {
                for (var i = 0; i < TextBoxCount; i++)
                    AddTextBox(i);
            }
        }

        private int TextBoxCount
        {
            get 
            {
                var count = ViewState["txtBoxCount"];
                return (count == null) ? 0 : (int) count;
            }
            set { ViewState["txtBoxCount"] = value; }
        }

        private void AddTextBox(int index)
        {
            var txt = new TextBox {ID = string.Concat("txtDynamic", index)};
            txt.Style.Add("display", "block");
            phControls.Controls.Add(txt);
        }

        protected void btnAddTextBox_Click(object sender, EventArgs e)
        {
            AddTextBox(TextBoxCount);
            TextBoxCount++;
        }

        protected void btnWriteValues_Click(object sender, EventArgs e)
        {
            foreach(var control in phControls.Controls)
            {
                var textBox = control as TextBox;
                if (textBox == null) continue;
                Response.Write(string.Concat(textBox.Text, "<br />"));
            }
        }
    }
}

既然你重新在每次回发的控件,输入到文本框的值将在每个回发坚持。我加了 btnWriteValues​​_Click 来快速演示如何读取值超出文本框的。

Since you are recreating the controls on each postback, the values entered into the textboxes will be persisted across each postback. I added btnWriteValues_Click to quickly demonstrate how to read the values out of the textboxes.

修改

我更新的例子添加包含一个文本框和一个删除按钮的面板。这里的窍门是,删除按钮不会删除容器面板,它只是使它不可见。这样做是使所有的控制ID的保持相同,因此数据输入撑与每个文本框。如果我们要完全删除文本框,被删除将一个TextBox向下移动的下一个回传文本框后的数据(只是为了更清楚地解释这一点,如果我们有TXT1,TXT2和txt3,我们删除TXT2,在接下来的回传,我们将创建两个文本框,TXT1和TXT2,这是txt3将丢失的值)。

EDIT
I updated the example to add a Panel containing a TextBox and a Remove Button. The trick here is that the Remove button does not delete the container Panel, it merely makes it not Visible. This is done so that all of the control IDs remain the same, so the data entered stays with each TextBox. If we were to remove the TextBox entirely, the data after the TextBox that was removed would shift down one TextBox on the next postback (just to explain this a little more clearly, if we have txt1, txt2 and txt3, and we remove txt2, on the next postback we'll create two textboxes, txt1 and txt2, and the value that was in txt3 would be lost).

public partial class DynamicControls : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            for (var i = 0; i < TextBoxCount; i++)
                AddTextBox(i);
        }
    }

    protected void btnAddTextBox_Click(object sender, EventArgs e)
    {
        AddTextBox(TextBoxCount);
        TextBoxCount++;
    }

    protected void btnWriteValues_Click(object sender, EventArgs e)
    {
        foreach(var control in phControls.Controls)
        {
            var panel = control as Panel;
            if (panel == null || !panel.Visible) continue;
            foreach (var control2 in panel.Controls)
            {
                var textBox = control2 as TextBox;
                if (textBox == null) continue;
                Response.Write(string.Concat(textBox.Text, "<br />"));
            }
        }
    }

    private int TextBoxCount
    {
        get 
        {
            var count = ViewState["txtBoxCount"];
            return (count == null) ? 0 : (int) count;
        }
        set { ViewState["txtBoxCount"] = value; }
    }

    private void AddTextBox(int index)
    {
        var panel = new Panel();
        panel.Controls.Add(new TextBox {ID = string.Concat("txtDynamic", index)});
        var btn = new Button { Text="Remove" };
        btn.Click += btnRemove_Click;
        panel.Controls.Add(btn);
        phControls.Controls.Add(panel);
    }

    private void btnRemove_Click(object sender, EventArgs e)
    {
        var btnRemove = sender as Button;
        if (btnRemove == null) return;
        btnRemove.Parent.Visible = false;
    }
}

这篇关于在ASP.Net持续动态控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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