我怎样才能重新实例化动态ASP.NET用户控件不使用数据库? [英] How can I re-instantiate dynamic ASP.NET user controls without using a database?

查看:171
本文介绍了我怎样才能重新实例化动态ASP.NET用户控件不使用数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在与使用动态的Web用户控件和我有一点麻烦搞清楚使用ViewState的或一些其他方法来重新实例上回发的控件的最佳方式我的应用程序的一部分,该工作不要求我在每次回发查询数据库。

I'm currently working with a part of my application that uses Dynamic Web User Controls and I'm having a bit of trouble figuring out the best way to re-instantiate the controls on postback by using ViewState or some other method that doesn't require me to query a database on each postback.

基本上我有我的网页上是一个包含面板抱着孩子的用户控件的变量数量和一个按钮,上面写着添加控制,其功能是pretty自我解释的用户控件。

Basically what I have on my page is a user control that contains a panel for holding a variable amount of child user controls and a button that says "Add Control" whose function is pretty self explanatory.

这孩子的用户控件是pretty简单;它只是一个删除按钮,下拉,并排列成一排的一个时间选择器控制。每当用户点击父控件添加控件按钮,一个新的行添加到包含的子控件面板。

The child user control is pretty simple; it's just a delete button, a drop down, and a time picker control arranged in a row. Whenever the user clicks the Add Control button on the parent control, a new 'row' is added to the panel containing the child controls.

我想要做的是能够添加和删除控件到此集合,修改值,并执行我需要'内存'做,而不必做一个数据库,任何调用任何操作。当我做了添加控件和填充他们的价值观,我想点击保存,从控制所有的数据保存/更新到数据库一次。目前我已经找到了唯一的解决方案是将数据库中的数据只需保存每个帖子后面,然后使用存储在数据库中的行重新实例上回发的控件。很显然,这会强制用户更改保存到数据库违背自己的意愿,并在他们要取消与控制工作,不保存自己的数据的情况下,额外的工作必须完成,以确保各行previously承诺都将被删除

What I would like to do is to be able to add and remove controls to this collection, modify values, and perform whatever operations I need to do 'in-memory' without having to do any calls to a database. When I am done adding controls and populating their values, I'd like to click "save" to save/update all the data from the controls to a database at once. Currently the only solution I have found is to simply save the data in the database each post back and then use the rows stored in the db to re-instantiate the controls on postback. Obviously, this forces the user to save changes to the DB against their will and in the event that they want to cancel working with the controls without saving their data, extra work must be done to ensure that the rows previously committed are deleted.

据我了解使用动态控制,我知道这是最好在生命周期的初始化阶段到控件添加到页面,然后填充他们的价值观在负载阶段。我还了解到,以确保您能坚持控件的视图状态的唯一途径是确保你给每个动态控制一个唯一的ID,并确保重新实例化控制时,分配给它的确切相同的ID。我还了解到,ViewState的不实际加载,直到在生命周期的初始化阶段之后。这是我的问题所在。我该如何存储和检索这些控件的名字,如果我无法使用视图状态,我不希望执行一个数据库的任何电话?这算哪门子采用ASP.net值甚至可以在内存中处理/批节能?

From what I've learned about using dynamic controls, I know it's best to add the controls to the page during the Init stage of the lifecycle and then populate their values in the load stage. I've also learned that the only way to make sure you can persist the control's viewstate is to make sure you give each dynamic control a unique ID and be sure to assign it the exact same ID when re instantiating the control. I've also learned that the ViewState doesn't actually get loaded until after the Init stage in the life cycle. This is where my problem lies. How do I store and retrieve the names of these controls if I am unable to use the viewstate and I do not want to perform any calls to a database? Is this sort of in-memory manipulation / batch saving of values even possible using ASP.net?

任何帮助是极大AP preciated,

Any help is greatly appreciated,

迈克

推荐答案

您可以存储你需要知道重新在会议期间举行一个集合中的控制什么最低限度。会议可在页面的初始化阶段。​​

You could store the bare minimum of what you need to know to recreate the controls in a collection held in session. Session is available during the init phases of the page.

下面是一个例子。它包括:

Here is an example for you. It consists of:

Default.aspx的,CS结果
  - 面板来存储用户控件结果
  - 添加控制按钮,将每次点击一次添加一个用户控件

Default.aspx, cs
- panel to store user controls
- "Add Control Button" which will add a user control each time it is clicked

TimeTeller.ascx,CS结果
   - 有一个名为SETTIME方法,设置在控制在规定的时间标签

TimeTeller.ascx, cs
- has a method called SetTime which sets a label on the control to a specified time.

Default.aspx的

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DynamicControlTest._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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel ID="pnlDynamicControls" runat="server">
        </asp:Panel>
        <br />
        <asp:Button ID="btnAddControl" runat="server" Text="Add User Control" 
            onclick="btnAddControl_Click" />
    </div>
    </form>
</body>
</html>

Default.aspx.cs:

Default.aspx.cs:

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

namespace DynamicControlTest
{
   public partial class _Default : System.Web.UI.Page
   {
      Dictionary<string, string> myControlList; // ID, Control ascx path

      protected void Page_Load(object sender, EventArgs e)
      {

      }

      protected override void OnInit(EventArgs e)
      {
         base.OnInit(e);

         if (!IsPostBack)
         {
            myControlList = new Dictionary<string, string>();
            Session["myControlList"] = myControlList;
         }
         else 
         {
            myControlList = (Dictionary<string, string>)Session["myControlList"];

            foreach (var registeredControlID in myControlList.Keys) 
            {
               UserControl controlToAdd = new UserControl();
               controlToAdd = (UserControl)controlToAdd.LoadControl(myControlList[registeredControlID]);
               controlToAdd.ID = registeredControlID;

               pnlDynamicControls.Controls.Add(controlToAdd);
            }
         }
      }

      protected void btnAddControl_Click(object sender, EventArgs e)
      {
         UserControl controlToAdd = new UserControl();
         controlToAdd = (UserControl)controlToAdd.LoadControl("TimeTeller.ascx");

         // Set a value to prove viewstate is working
         ((TimeTeller)controlToAdd).SetTime(DateTime.Now);
         controlToAdd.ID = Guid.NewGuid().ToString(); // does not have to be a guid, just something unique to avoid name collision.

         pnlDynamicControls.Controls.Add(controlToAdd);

         myControlList.Add(controlToAdd.ID, controlToAdd.AppRelativeVirtualPath);
      }
   }
}

TimeTeller.ascx

TimeTeller.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TimeTeller.ascx.cs" Inherits="DynamicControlTest.TimeTeller" %>
<asp:Label ID="lblTime" runat="server"/>

TimeTeller.ascx.cs

TimeTeller.ascx.cs

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

namespace DynamicControlTest
{
   public partial class TimeTeller : System.Web.UI.UserControl
   {
      protected void Page_Load(object sender, EventArgs e)
      {

      }

      public void SetTime(DateTime time) 
      {
         lblTime.Text = time.ToString();
      }

      protected override void LoadViewState(object savedState)
      {
         base.LoadViewState(savedState);
         lblTime.Text = (string)ViewState["lblTime"];
      }

      protected override object SaveViewState()
      {
         ViewState["lblTime"] = lblTime.Text;
         return base.SaveViewState();
      }
   }
}  

正如你可以看到,我还是要管理我的用户控件的内部视图状态,但视图状态包被保存到页面,交还给上回发的控制。我觉得要注意的是我的解决方案是非常接近大卫是非常重要的。在我的例子唯一的主要区别在于它使用的会话,而不是视图状态来存储控制信息。这样的事情在初始化阶段发生。要注意,此溶液占用更多的服务器资源是很重要的,因此,它可能无法在这取决于你缩放策略某些情况下适当。

As you can see, I still have to manage the internal viewstate of my user control, but the viewstate bag is being saved to the page and handed back to the control on postback. I think it is important to note that my solution is very close to David's. The only major difference in my example is that it's using session instead of viewstate to store the control info. This allows things to happen during the initialization phase. It is important to note that this solution takes up more server resources, therefore it may not be appropriate in some situations depending on your scaling strategy.

这篇关于我怎样才能重新实例化动态ASP.NET用户控件不使用数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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