UserControl with UpdatePanel programmatically create ScriptManager possible? - asp.net

I'd like to use an UpdatePanel in my UserControl. The problem is the .aspx page the control is dropped on will NOT have a ScriptManager. I will need to create the ScriptManager in the UserControl. However if the UserControl is used, say twice on the page, then placing a ScriptManager won't work because you can only initialize ScriptManager once.
In other UserControls where I needed ScriptManager (I was using AJAX Toolkit Extensions) I was able to use this code:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Page.Init += new EventHandler(Page_Init);
}
void Page_Init(object sender, EventArgs e)
{
if (Page.Form != null && ScriptManager.GetCurrent(Page) == null)
Page.Form.Controls.AddAt(0, new ScriptManager());
}
..worked great, but not for the UpdatePanel case.
Note, I am NOT using Master Pages
(Another approach I was thinking of, but can't figure out how to do, is to programmatically create the UserControl inside an UpdatePanel.)

I do not think this is possible. I have tried it several different ways. You might have to bite the bullet and put a scriptmanager in your page.

What is the reason it doesn't work? Are you getting an exception from the UpdatePanel that a ScriptManager is required? Are you using System.Web.Extensions 1.0 or 3.5? I say that because a change was made to UpdatePanel in 3.5 that causes its content template to instantiate prior to OnInit, so I don't see an obvious reason why that wouldn't work. If there is an exception it would be helpful to see the stack trace.

I am hitting this same problem. The problem is that you need to add the scriptmanager before the OnInit stage - as far as I can see it needs to be done at the preinit stage. You can see this by adding a load of overrides - I found the the page got through the preinit ok, then went to the addedcontrol event and it was at (or just after, but this point makes sense) that the "You need a scriptmanager" gets thrown. I am struggling to find how to add an event handler to the Page.PreInit event from a child usercontrol as the WUCs don't have a PreInit event. Even the WUC constructor doesn't fire before that point and in the constructor the page object is null so you can't add it there. Even at the AddedControl stage of the WUC, you still don't seem to be able to access the main page ( ScriptManager oSCM = ScriptManager.GetCurrent(Page); returns null) so you can't seem to add the scriptmanager, if you need to, before the error is thrown.
/edit:-
As far as I can see it (and I've had no answer to this on the asp.net forums - surprise, surprise) the WUC doesn't start kicking in it's methods/events until after the parent's preinit stage, so there's 2 ways of doing this.
1) The way I think I would do this is to not put any content in the designer that requires the scriptmanager and to put placeholders where such content needs to go. Then in the wuc load you use the ScriptManager.GetCurrent to see if there's one already there and then create it if not. Then you dynamically add the content that requires the SCM. Something like this:-
<%# Control Language="C#" AutoEventWireup="true" CodeFile="wucTestExample.ascx.cs" Inherits="wucTestExample" %>
<asp:PlaceHolder ID="plcAJAX" runat="server" />
<asp:Label ID="lblGeneral" runat="server" Text="This is another label" />
----------------code behind---------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class wucTestExample : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager oSCM = ScriptManager.GetCurrent(this.Page);
if (oSCM == null)
{
oSCM = new ScriptManager();
oSCM.ID = "scmAJAX";
oSCM.EnablePartialRendering = true;
this.plcAJAX.Controls.AddAt(0, oSCM);
}
UpdatePanel udpMain = new UpdatePanel();
udpMain.ID = "udpMain";
TextBox txtMain = new TextBox();
txtMain.ID = "txtMain";
// other attrbutes here
Button btnPostback = new Button();
btnPostback.ID = "btnPostback";
btnPostback.Click += new EventHandler(btnPostback_Click);
btnPostback.Text = "Partial Postback";
Label lblPostback = new Label();
lblPostback.ID = "lblPostback";
lblPostback.Text = "initial postback";
udpMain.ContentTemplateContainer.Controls.Add(txtMain);
udpMain.ContentTemplateContainer.Controls.Add(btnPostback);
udpMain.ContentTemplateContainer.Controls.Add(lblPostback);
this.plcAJAX.Controls.Add(udpMain);
}
void btnPostback_Click(object sender, EventArgs e)
{
// implement button code here
Label lblPostback = (Label)this.plcAJAX.FindControl("lblPostback");
if (lblPostback != null)
{
lblPostback.Text = String.Format("WUC POstback at : {0}", DateTime.Now.ToLongTimeString());
}
}
}
then use it thus:-
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="TestExampleNoSCM.aspx.cs" Inherits="TestExampleNoSCM" %>
<%# Register Src="~/wucTestExample.ascx" TagName="wucTestExample" TagPrefix="ucTE" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<%--<asp:ScriptManager ID="scmAJAX" runat="server" />--%>
<asp:Label ID="lblLoadTime" runat="server" />
<ucTE:wucTestExample ID="wucTestExample" runat="server" />
</asp:Content>
----------------code behind---------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class TestExampleNoSCM : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.lblLoadTime.Text = String.Format("Page load at: {0}",DateTime.Now.ToLongTimeString());
}
}
So if you comment or uncomment the SCM in the parent page, the WUC still works either way.
2) I've seen another option where an update panel was needed and the programmer created all the controls in the designer and then looped round them in the page load (after creating the SCM, if needed, and the UDP and added all the controls on the WUC UDP, before then adding that to to placeholder, but this strikes me as rather dangerous as it seems to be double-instantiating control, and I think it may come back to bite them on the bum...
The downside with method 1 is that it's more work to create everything in your updatepanel programmatically, but if you really want to build a self-dependent WUC, that seems to be your price (and hopefully, the WUC shouldn't be that complicated, anyway). Personally, I think in my app (as the WUC won't be used outside it) I'll just make sure I add in an SCM where needed on the main page.
One other, final, note I would pitch in - I've seen people saying "add it to the master page" - this seems to be a particularly bad idea, IMHO, unless every page in your app needs the SCM as it will add a whole new level of bloat to your pages, and that doesn't seem to be a good idea as ASP.NET seems to have a good level of bloat already...

Instead of dynamically adding a ScriptManager if none exists on the page, simply do the opposite: add a ScriptManager to your ASCX and get rid of it if there's one already on the page. So...
protected override void OnInit(EventArgs e) {
base.OnInit(e);
AdjustScriptManager();
}
private void AdjustScriptManager() {
if (ScriptManager.GetCurrent(Page) != null) {
ScriptManager1 = null;
}
}
UPDATE:
Nah, after further testing this won't work, as ScriptManager1 = null does nothing helpful. If there is a way to do this (or to remove the Page control), please comment.

Solution: you can add a scriptmanager dynamically in the usercontrol by checking if the current page does not already contain a ScriptManager. Here's how:)
In the UserControl (ascx) html put this:
<asp:PlaceHolder ID="pHolder" runat="server" />
And in the code behind (ascx.cs):
//insert Scriptmanager dynamically only IF it does not already exist
private void createScriptManager(System.EventArgs e)
{
// the GetCurrent() method will return a ScriptManager from the Page
if (System.Web.UI.AjaxScriptManager.GetCurrent(this.Page) == null)
{
System.Web.UI.AjaxScriptManager manager = new System.Web.UI.AjaxScriptManager();
manager.EnablePartialRendering = true;
pHolder.Controls.Add(manager);
}
}
// call the above method from the usercontrol's OnInit
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
createScriptManager(e);
base.OnInit(e);
}
Sometimes it is necessary to define a ScriptManager dynamically. In my case I am using a usercontrol that will be put into different pages, but some of these pages already contain a ScriptManager and some dont, so how will my usercontrol know if it should define its own ScriptManager? The beauty of the above code is that the usercontrol adds a scriptmanager only if there isn't already one on the page.
Note: the System.Web.UI.AjaxScriptManager may be replaced with System.Web.UI.ScriptManager if you use an older version of Ajax.

Related

Master Page load not being called

public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if(System.Web.HttpContext.Current.User.Identity.Name != "") //if (!Page.IsPostBack)
{
BusinessLayer.ShoppingCart cart = new BusinessLayer.ShoppingCart();
int count = cart.getNoOfProducts(System.Web.HttpContext.Current.User.Identity.Name);
Label lblCart = (Label)Master.FindControl("lblCartNo");
lblCart.Text = " (" + count + ")";
}
}
}
I placed a breakpoint and this code is never called (even without the if statement), also I was not able to find the label which is located in the master page
In order for Page_Load to be called, make sure that in your MasterPage.aspx have AutoEventWireup="true":
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="Mysite.Website.Templates.MasterPages.Site" %>
Make sure that MasterPage.aspx Inherits attribute matches your code-behind namespace and class name, as well as your .designer.cs namespace and class.
If the aspx and code-behind files all are wired up correctly, then you should be able to remove the FindControl statement.
The Page_Load event for your master page should definitely be firing. Not sure why your breakpoint isn't being hit, but to double check, I'd recommend trying something a bit more brute force to make absolutely sure that the method is definitely not being called:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Page_Load");
Response.End();
}
Your label may not be found due to the way controls are nested as Master.FindControl won't work if the control resides inside another control. I'd recommend checking out "Finding controls inside of nested master pages" which has a useful helper method that can be used to search for controls recursively.

Custom event not working when registered in an ASPX file

I am trying to register a custom event I added to a user control.
I can do this in code behind, but not in the aspx file.
What am I doing wrong?
Thanks!
The user control:
public delegate void MemberSelectedEventHandler(object sender, string fullMemberName);
public partial class WebUserControl1 : System.Web.UI.UserControl
{
public event MemberSelectedEventHandler OnMemberSelected;
protected void Button_OnClick(object sender, EventArgs e)
{
if (OnMemberSelected != null)
{
OnMemberSelected(this, "Peter");
}
}
}
This works (code behind of aspx page):
MyMemberControl.OnMemberSelected += new MemberSelectedEventHandler(MyMemberControl_OnMemberSelected);
But this doesn't (aspx page):
<scn:MemberControl OnMemberSelected="MemberControl_OnMemberSelected" runat="server" ID="MyMemberControl" />
In the markup you need to prefix your event property with On so the page will know to register the event. Morzel had the answer though it's not stated explicitly.
<scn:MemberControl OnOnMemberSelected="MemberControl_OnMemberSelected" runat="server" ID="MyMemberControl" />
OnOnMemberSelected should cause your handler to be invoked as expected.
First of all I have to take a bit note: When you make a custom event, you don't need to name it with 'On' prefix. .Net framework adds this prefix and the markup intellisense will show you OnOnMemberSelected.
I don't know if it needs, but try to put the delegate declaration inside your WebUserControl1 class. I always do this.
Markup intellisense reacting really slow and I don't see if it deterministic when popullates intellisense information again.
Sum of all:
- put the delegate definition into your class.
- build
- insert your markup code.
If intellisense doesn't work immediatelly I think it will works.

Difference with creating and adding controls in PreInit Init

There's tons of info on the web about the ASP.NET life cycle, but i can't seem to figure out when to dynamically add controls to the page.
In general there are two situations; an aspx page with a masterpage, and one without. The book i'm currently reading (70-515 self prep) says to add controls to a page without a master page in the preinit eventhandler. To dynamically add controls to a contentpage, i should place that logic in the init eventhandler.
According to MSDN (http://msdn.microsoft.com/en-us/library/ms178472.aspx) I should create or recreate dynamic controls in the preinit eventhandler, and only read or initialize properties of controls in the init eventhandler (which makes most sense to me). Googling around I see lots of people using the init eventhandler to add controls.
So, i'm a little bit lost here - what is the correct way? And when using the preinit eventhandler, how could you add controls to your page when all controls are null? For instance, when you need to add a dynamically created textbox to a panel control?
Kind regards,
Unless you need to play around with setting control properties prior to tracking ViewState, I would personally go ahead and place my dynamic control addition logic in the OnInit event.
If you really want to dynamically add a control during the PreInit (when using master page) you can always do something like this:
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
TextBox textBox = new TextBox();
textBox.Text = "Dynamic TextBox";
textBox.Width = 100;
textBox.ReadOnly = false;
var master = this.Master;
plcHolder.Controls.Add(textBox);
textBox.ApplyStyleSheetSkin(this.Page);
}
accessing the "Master" property would instantiate the controls
and it should work, but you get nested master pages scenarios (this.Master.Master ...), update panels and so on.
This might be relevant and helpful: http://weblogs.asp.net/ysolodkyy/archive/2007/10/09/master-page-and-preinit.aspx
Moreover, one reason I can think of (besides following the defined page lifecycle) MS recommends that we place all the logic for dynamic control creation in the Preinit event so we can take advantage of the theme service, which will apply all available skin properties automatically for us, before the Init event takes place.
Say your markup looks something like that:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Trace="true" Inherits="_Default" Theme="Test" %>
...
<form id="form1" runat="server">
<div>
<p>
<asp:TextBox ID="TextBox1" runat="server" TextMode="Password" Text="Control TextBox"></asp:TextBox>
</p>
<p>
<asp:PlaceHolder ID="plcHolder" runat="server"></asp:PlaceHolder>
</p>
</div>
</form>...
and you have a skin like this:
<asp:TextBox runat="server" BackColor="Yellow" Wrap="false" Text="Skin property!" > </asp:TextBox>
Just add this to your code behind:
private TextBox tb1;
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
tb1 = new TextBox();
tb1.Text = "PreInit Dynamic TextBox";
Trace.Write(String.Format("tb1 Wrap Property-> {0}",tb1.Wrap));
Trace.Write(String.Format("tb1 Text Property-> {0}", tb1.Text));
Trace.Write("Add tb1 to the placeholder.");
plcHolder.Controls.Add(tb1);
Trace.Write(String.Format("tb1 Wrap Property-> {0}", tb1.Wrap));
Trace.Write(String.Format("tb1 Text Property-> {0}", tb1.Text));
}
protected override void OnInit(EventArgs e)
{
Trace.Write(String.Format("tb1 Wrap Property-> {0}", tb1.Wrap));
Trace.Write(String.Format("tb1 Text Property-> {0}", tb1.Text));
base.OnInit(e);
}
protected void Page_Load(object sender, EventArgs e)
{
Trace.Write(String.Format("tb1 Wrap Property-> {0}", tb1.Wrap));
Trace.Write(String.Format("tb1 Text Property-> {0}", tb1.Text));
}
You will notice how before going into the Init event all skin properties are already applied to the dynamically created textbox :)
The PreInit event was new to me, but I guess it makes sense, so that you have an intermediary step in between the loading of controls and viewstate load to do additional work. We've used init event to load dynamic controls and this has always worked for us with no issues. I think you'll be OK with either, but if MS recommends PreInit, I'd say go that route. THis way, in Init, you can do any additional work you may need and separate out the routine that creates the UI vs. the routine that may update it before viewstate load.
HTH.

Reusable Page_PreRender function in asp.net

I have a function which sets my linkbutton as the default button for a panel.
protected void Page_PreRender(object sender, EventArgs e)
{
string addClickFunctionScript = #"function addClickFunction(id) {
var b = document.getElementById(id);
if (b && typeof(b.click) == 'undefined')
b.click = function() {
var result = true;
if (b.onclick) result = b.onclick();
if (typeof(result) == 'undefined' || result)
eval(b.getAttribute('href'));
}
};";
string clickScript = String.Format("addClickFunction('{0}');", lbHello.ClientID);
Page.ClientScript.RegisterStartupScript(this.GetType(), "addClickFunctionScript", addClickFunctionScript, true);
Page.ClientScript.RegisterStartupScript(this.GetType(), "click_" + lbHello.ClientID, clickScript, true);
}
This works fine. How to make this reusable to all my pages of my application. One page can have multiple linkbuttons and multiple panels.... Any suggestion...
The cleanest way would be to use a custom server control that inherits from LinkButton. In fact this seems to be in line with the blog post from your earlier question. All you need to do is override the OnPreRender event and paste the code you have while changing lbHello.ClientID to this.ClientID to refer to the specific instance of that control. It should not take more than 10 minutes to set this up. Once this is done, you can use as many of the controls as you want on one page and easily support it throughout your application's various pages.
You might find this MSDN article helpful when following my instructions below, specifically the "Creating the Server Control" section: Walkthrough: Developing and Using a Custom Web Server Control. Here's a step by step guide to accomplishing this:
In your existing solution add a new ASP.NET Server Control project (right click on your solution from the Solution Explorer -> Add New Project -> ASP.NET Server Control). Name it LinkButtonDefault (you're free to change the name, of course).
Rename ServerControl1.cs to LinkButtonDefault.cs
Rename the namespace in the file to CustomControls
Perform steps 12-14 in the MSDN article by opening the AssemblyInfo.cs file (contained in the Properties folder of the project). Add this line at the bottom of the file: [assembly: TagPrefix("CustomControls", "CC")]
In LinkButtonDefault.cs add this code to override the OnPreRender event:
Code (notice the use of this.ClientID):
protected override void OnPreRender(EventArgs e)
{
string addClickFunctionScript = #"function addClickFunction(id) {
var b = document.getElementById(id);
if (b && typeof(b.click) == 'undefined')
b.click = function() {
var result = true;
if (b.onclick) result = b.onclick();
if (typeof(result) == 'undefined' || result)
eval(b.getAttribute('href'));
}
};";
string clickScript = String.Format("addClickFunction('{0}');", this.ClientID);
Page.ClientScript.RegisterStartupScript(this.GetType(), "addClickFunctionScript", addClickFunctionScript, true);
Page.ClientScript.RegisterStartupScript(this.GetType(), "click_" + this.ClientID, clickScript, true);
base.OnPreRender(e);
}
You may also want to update the generated attribute code above the class declaration that starts with [ToolboxData("<{0}: to use LinkButtonDefault instead of ServerControl1. That's it for the new Server Control project. I highly recommend reading the aforementioned MSDN article to take advantage of other capabilities, such as adding controls to the toolbox if you have a need to do so.
After completing these steps you should have a LinkButtonDefault.cs file that resembles this:
using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CustomControls
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:LinkButtonDefault runat=server></{0}:LinkButtonDefault>")]
public class LinkButtonDefault : LinkButton
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Text
{
get
{
String s = (String)ViewState["Text"];
return ((s == null) ? "[" + this.ID + "]" : s);
}
set
{
ViewState["Text"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
output.Write(Text);
}
protected override void OnPreRender(EventArgs e)
{
string addClickFunctionScript = #"function addClickFunction(id) {
var b = document.getElementById(id);
if (b && typeof(b.click) == 'undefined')
b.click = function() {
var result = true;
if (b.onclick) result = b.onclick();
if (typeof(result) == 'undefined' || result)
eval(b.getAttribute('href'));
}
};";
string clickScript = String.Format("addClickFunction('{0}');", this.ClientID);
Page.ClientScript.RegisterStartupScript(this.GetType(), "addClickFunctionScript", addClickFunctionScript, true);
Page.ClientScript.RegisterStartupScript(this.GetType(), "click_" + this.ClientID, clickScript, true);
base.OnPreRender(e);
}
}
}
Now return to your web application and add a reference to the CustomControls project. You should be able to do this from the Add Reference's Project tab since I suggested adding the above project to your existing solution. If you want you could've built the above project in its own solution then you would add a reference to it's .dll file by using the Browse tab. Once a reference has been added you are ready to use the new LinkButtonDefault control.
To use the controls you can use the # Register directive on each page the control will be used, or you can add it to the Web.config and gain easy reference to it throughout your application. I will show you both methods below. Based on your question I think you'll want to add it to the Web.config. Refer to the MSDN article and you will find this information half way down the page under "The Tag Prefix" section.
Using # Register directive:
Go to your desired .aspx page and add the Register directive to the top of each page you want to use the control in:
<%# Register Assembly="CustomControls" Namespace="CustomControls" TagPrefix="CC" %>
On the same page, you may now use multiple instances of the control. Here's an example:
<p><strong>1st Panel:</strong></p>
<asp:Label runat="server" ID="helloLabel" />
<asp:Panel ID="Panel1" runat="server" DefaultButton="lbHello">
First name:
<asp:TextBox runat="server" ID="txtFirstName" />
<CC:LinkButtonDefault ID="lbHello" runat="server" Text="Click me" OnClick="lbHello_Click"
OnClientClick="alert('Hello, World!');" />
</asp:Panel>
<p><strong>2nd Panel:</strong></p>
<asp:Label runat="server" ID="fooBarLabel" />
<asp:Panel ID="Panel2" runat="server" DefaultButton="lbFooBar">
Other:
<asp:TextBox runat="server" ID="TextBox1" />
<CC:LinkButtonDefault ID="lbFooBar" runat="server" Text="Click me" OnClick="lbFooBar_Click" />
</asp:Panel>
In the code behind (.aspx.cs) you would need to add:
protected void Page_Load(object sender, EventArgs e)
{
// example of adding onClick programmatically
lbFooBar.Attributes.Add("onClick", "alert('Foo Bar!');");
}
protected void lbHello_Click(object sender, EventArgs e)
{
helloLabel.Text = String.Format("Hello, {0}", txtFirstName.Text);
}
protected void lbFooBar_Click(object sender, EventArgs e)
{
fooBarLabel.Text = String.Format("FooBar: {0}", TextBox1.Text);
}
Using Web.config:
To use the Web.config keep the exact same markup and code used in the above example. Follow these steps:
Remove the # Register directive used on the .aspx markup.
Open the Web.config file for your web application.
Locate the <system.web>...</system.web> section.
Add the following mapping to that section:
Mapping:
<pages>
<controls>
<add assembly="CustomControls" namespace="CustomControls" tagPrefix="CC" />
</controls>
</pages>
Recompile and everything should build successfully. With this in place you no longer need to specify the # Register directive on each individual page.
If you get stuck and have any questions let me know. Just read over everything above carefully since it's a long post with lots of code.
You could create a class (let's call it Foo) that derives from System.Web.UI.Page and abstract your method to a point where it is reusable. All your ContentPages should derive from Foo instead of System.Web.UI.Page
My recommendation would be to either use a master page, or break the code out into a static function that takes a System.Web.UI.Page object as a parameter. Of course, you could always use inheritance (which will work), but you will lose the ability to layout your page using drag-and-drop design time functionality, since the VS.NET web form designer does a big freakout with ASPX pages that don't derive from System.Web.UI.Page or System.Web.UI.MasterPage directly.

How can I re-instantiate dynamic ASP.NET user controls without using a database?

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.
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.
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.
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.
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?
Any help is greatly appreciated,
Mike
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
- panel to store user controls
- "Add Control Button" which will add a user control each time it is clicked
TimeTeller.ascx, cs
- has a method called SetTime which sets a label on the control to a specified time.
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:
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
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TimeTeller.ascx.cs" Inherits="DynamicControlTest.TimeTeller" %>
<asp:Label ID="lblTime" runat="server"/>
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.
I have done this in the past. I have not had to do this since the days of .NET 1.1, but the principal removes the same.
I did it on Page_Load not Init have to reload the controls that you created on the last page cycle.
First you need to keep track of the controls you have created on each page cycle. This includes type, name etc. . .
Then on each page load you need to rebuild them.
You do that by re-creating the control, assinging it the exact same id, add it to the sampe place on the page and finally in the ViewState["LoadedControl"] to the control type.
Here is the code I used, I only did this with User Controls that I created. I have not tried this with an ASP.NET control, but I think it would work the same.
In this case I have an ArrayList of Triplets (keep in mind this is .NET 1.1) adn the first item was a PageView ID. You might not need that for your application.
protected void Page_Load(object sender, System.EventArgs e)
{
//**********************************************************
//* dynCtlArray will hold a triplet with the PageViewID, *
//* ControlID, and the Control Name *
//**********************************************************
ArrayList dynCtlArray = (ArrayList)this.ViewState["dynCtlArray"];
if (dynCtlArray != null)
{
foreach (object obj in dynCtlArray)
{
Triplet ctrlInfo = (Triplet)obj;
DynamicLoadControl(ctrlInfo);
}
}
}
private void DynamicLoadControl(Triplet ctrlInfo)
{
// ERROR HANDLING REMOVED FOR ANSWER BECAUSE IT IS NOT IMPORTANT YOU SHOULD HANDLE ERRORS IN THIS METHOD
Control ctrl = this.LoadControl(Request.ApplicationPath
+ "/UC/" + (string)ctrlInfo.Third);
ctrl.ID = (string)ctrlInfo.Second;
// Create New PageView Item
Telerik.WebControls.PageView pvItem = this.RadMultiPage1.PageViews[(int)ctrlInfo.First];
pvItem.Controls.Add(ctrl);
/******************************************************
* The ControlName must be preserved to track the *
* currently loaded control *
* ****************************************************/
ViewState["LoadedControl"] = (string)ctrlInfo.Third;
}
private void RegisterDynControl(Triplet trip)
{
ArrayList dynCtlArray = (ArrayList)this.ViewState["dynCtlArray"];
if (dynCtlArray == null)
{
dynCtlArray = new ArrayList();
this.ViewState.Add("dynCtlArray", dynCtlArray);
}
dynCtlArray.Add(trip);
}
In some method on your page
// Create new Control
Control ctrl = Page.LoadControl("../UC/MyUserControl.ascx");
// . . . snip .. .
// Create Triplet
Triplet ctrlInfo = new Triplet(0, ctrl.ID, "MyUserControl.ascx");
// RegisterDynControl to ViewState
RegisterDynControl(ctrlInfo);
// . . . snip .. .
To access the controls to save there information you will have to do a this.Page.FindControl('');
I implemented a page very similar to Daniel's example, but could not use Session due to technical constraints. However, I found that by using an field to the page, I could post back and retrieve its value during the Page_Init event.

Resources