How to create permanent controls in asp.net codebehind - asp.net

I have to add some controls to my project master page in code behind,but I want to keep them even after post back.how can i do this? I've searched about it and I think that i have to use preinit ,but I don't Know how, and I don't know if master Page has preinit.
<form id="form1" runat="server">
<asp:ScriptManager ID="MainScriptmanager" runat="server" EnablePartialRendering="true" />
<asp:UpdatePanel ID="MasterContentUpdatePanel" runat="server" UpdateMode="conditional">
<ContentTemplate>
<asp:TabContainer ID="MainTabContainer" runat="server" ActiveTabIndex="1" TabStripPlacement="Bottom">
</asp:TabContainer>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
protected void Button1_Click(object sender, EventArgs e)
{
tabCount = tabCount + 1;
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
tab.ID = "tab" + Convert.ToString(tabCount);
tab.HeaderText = "tab" + Convert.ToString(tabCount);
MainTabContainer.Tabs.Add(tab);
}

What keeps you from creating the controls and adding it to a, say, panel, in code behind? Create a panel in designer, name it, and create/add all the controls to in code behind wherever you need. Viewstate will preserve their contents between postbacks, you don't need to do anything extra.

You need to recreate the tabs on each postback.
E.g. you might store the count of tabs in ViewState.
Then on PostBack, you add the tabs e.g. in your Page_Load event handler:
var tabCount = ... get it from ViewState
for(int i=0; i<tabCount; i++)
{
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
tab.ID = "tab" + Convert.ToString(i+1);
tab.HeaderText = "tab" + Convert.ToString(i+1);
MainTabContainer.Tabs.Add(tab);
}

Related

ASP.Net AJAX UpdatePanel not working with Repeater and RadioButtons

I have a repeater which includes a radio button in each item, and the whole thing sites inside an update panel. When I select a radio button the whole page reloads. Why is it not just updating the update panel. I've reduced this to a pretty simple example to avoid clutter. Code here...
ASPX...
<asp:ScriptManager ID="SM1" runat="server" />
<asp:UpdatePanel ID="up1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Repeater runat="server" ID="history">
<ItemTemplate>
<asp:RadioButton runat="server" ID="radioButton" AutoPostBack="true" GroupName="HistoryGroup" OnCheckedChanged="RadioButton_CheckChanged" /><br />
</ItemTemplate>
</asp:Repeater>
<p><asp:Literal runat="server" ID="output" /></p>
</ContentTemplate>
</asp:UpdatePanel>
Code...
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<int> list = new List<int>();
for (int i = 0; i < 20; i++)
list.Add(i);
history.DataSource = list.ToArray();
history.DataBind();
}
}
protected void RadioButton_CheckChanged(Object sender, EventArgs e)
{
output.Text = DateTime.Now.ToString();
}
}
Setting ClientIDMode=Auto on the RadioButton should fix it (it's an infamous .NET bug, http://connect.microsoft.com/VisualStudio/feedback/details/584991/clientidmode-static-in-updatepanel-fails-to-do-async-postback)
please add up1.Update() after output.Text = DateTime.Now.ToString(). Your RadioButton is not the trigger for updatepanel
Turns out the solution was to remove the GroupName from the RadioButton. When I remove this tag it fires asynchronously and just updates the panel. I don't actually need this tag anyway (due to the known bug where GroupName doesn't work on RadioButtons in Repeaters) as I handle the grouping within my click event (i.e. uncheck any other RadioButtons of the same name in other repeater items).

How do I load two ASP.NET UserControls on Demand?

I want load two user controls on demand.
asp:UpdatePanel ID="UpdatePanel1" runat="server"
ContentTemplate
asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false"
OnClick="Button1_Click" /
div id='Div_UserControlPlace' enableviewstate="true" runat="server"
/div
/ContentTemplate
Triggers
asp:PostBackTrigger ControlID="Button1" /
/Triggers
/asp:UpdatePanel
asp:UpdatePanel ID="UpdatePanel2" runat="server"
ContentTemplate
asp:Button ID="Button2" runat="server" Text="Button" UseSubmitBehavior="false"
OnClick="Button2_Click" /
div id='Div_UserControlPlace2' enableviewstate="true" runat="server"
/div
/ContentTemplate
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Control FeaturedProductUserControl = new Control();
FeaturedProductUserControl = LoadControl("WebUserControl1.ascx");
FeaturedProductUserControl.EnableViewState = true;
Div_UserControlPlace.Controls.Add(FeaturedProductUserControl);
}
protected void Button2_Click(object sender, EventArgs e)
{
Control FeaturedProductUserControl2 = new Control();
FeaturedProductUserControl2 = LoadControl("WebUserControl2.ascx");
FeaturedProductUserControl2.EnableViewState = true;
Div_UserControlPlace2.Controls.Add(FeaturedProductUserControl2);
}
I load the first user control by clicking on the first button - this works properly but when I click on the other button to load the second UserControl, the first UserControl disappears and the second UserControl loads.
Thanks
IFA_User
You should use the Placeholder control to dynamically add your controls to the form.
Take a look at my last responses about dynamic controls:
OnClick event of dynamically created LinkButtons is not working
Dynamically Added DropDownlists Are Not Firing SelectedIndexChanged Event
Dynamically create an ImageButton
Now I already have some code working for demo purpose, each dynamic user controls keeps its state across post backs
This is the output:
ASPX
<asp:PlaceHolder runat="server" ID="addresses" /><br />
<asp:Button Text="Add Address" runat="server" ID="addAddress" OnClick="addAddress_Click" />
ASPX Code behind
protected void Page_PreLoad(object sender, EventArgs e)
{
for (int i = 0; i < this.DynamicControlsCount; i++)
{
var c = this.LoadControl("~/AddressControl.ascx");
this.addresses.Controls.Add(c);
}
}
protected void addAddress_Click(object sender, EventArgs e)
{
this.DynamicControlsCount++;
var c = this.LoadControl("~/AddressControl.ascx");
this.addresses.Controls.Add(c);
}
protected int DynamicControlsCount
{
get
{
if (this.ViewState["ac"] == null)
{
return 0;
}
return (int)this.ViewState["ac"];
}
set
{
this.ViewState["ac"] = value;
}
}
ASCX
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddressControl.ascx.cs" Inherits="WebApplication1.AddressControl" %>
<asp:Panel ID="Panel1" runat="server" GroupingText="Address" DefaultButton="btnSave">
Street: <asp:TextBox runat="server" ID="txtStreet" /><br />
City: <asp:TextBox runat="server" ID="txtCity" /><br />
<asp:Button Text="Save" runat="server" ID="btnSave" OnClick="btnSave_Click" />
</asp:Panel>
<asp:Panel runat="server" GroupingText="Address Summary" Visible="false" ID="summary">
<asp:Label ID="lblStreet" runat="server" /><br />
<asp:Label ID="lblCity" runat="server" />
</asp:Panel>
ASCX Code behind
protected void btnSave_Click(object sender, EventArgs e)
{
this.summary.Visible = true;
this.lblCity.Text = "Selected city: " + this.txtCity.Text;
this.lblStreet.Text = "Selected street: " + this.txtStreet.Text;
}
When a user control is created in the HTML, asp.net will persist across postbacks without any user interaction. But if you are loading them programatically (dynamically), they will not persist accross postbacks. So if you load them programmatically, you have the added task of persisting them programmatically as well. Use the ViewState (or Session I suppose) to store what has been loaded and perhaps any other necessary information that needs to be loaded between postbacks. Every single postback will require you to reload every control or else they will disappear.
There are couple of ways of doing it:
U can load the UserControls using Ajax. Benefit of using Ajax, is ur page does not get post back, thus for example, on click event of Button1, call a ajax(traditional/Jquery) to load UserControl1, and on button click of Button2 User control2.
Put the two button in two different updated panel, by doing this the click event will only refresh a part of ur page.
U have to save somewhere (ViewState/Session),which buttons are clicked, and upon clicking of any button check the value of that variable, and explicit load the control.
Points to note - If u want to get ur data back when ur page made a complete postback, then u have to add the controls keeping in mind the Page load event cycle.

lazy loading asp.net Ajax Control Toolkit accordion

I am using the asp.net Ajax Control Toolkit accordion (http://www.asp.net/ajaxlibrary/act_Accordion.ashx) and each accordion pane contains quite a lof information.
All that info is generated in the page but it is not shown because the toolkit gives the non active panes a
(style="display:none;)
But because the info is in the page, it becomes a very heavy page to load.
I am looking for a way to load the panes on-demand: so only if the user clicks the pane an ajax request is send and the pane is loaded and expanded.
Can this be done with this control or should i choose a different accordion? Any help or suggestions appreciated.
update
Currently the Accordion is created with two, nested, repeaters. The first repeater loops over the categories and creates a panel for each category. The second repeater repeates inside each panel takes the content for one category and creates the content of the panel.
Pleun
I don't have the points to comment and ask you questions. Sorry. :(
My questions are in regard to how you plan to create and populate the Accordion.
Will you create panes by hand using markup in the IDE or will you bind the Accordion to a DataSource that will dynamically create the panes you need?
Will you have 3 separate DataSources or a different combination of the following:
1.) DataSource to initialize the number of panels and populate only the panel's Header information.
2.) DataSource to populate the Static Content of all panels on first load.
3.) DataSource to populate the Lazy-Loaded Content of a single panel the user clicks to expand.
With your answers I hope to update this answer with a real one. Thanks.
Update: This is achievable with the Ajax Control Toolkit's Accordion.
I have some very basic code below as proof of concept. It could be smoother, but I'll leave it up to you to add a "Loading" image using the UpdatingProgress control if you find it necessary.
The Accordion in the Aspx markup:
(Notice the UpdatePanels - you can replace them with callbacks if you want, I just wanted to keep the answer simple)
<asp:Accordion ID="acc_Accordion" runat="server" RequireOpenedPane="false"
SelectedIndex="-1" onitemcommand="acc_Accordion_ItemCommand" >
<HeaderTemplate>
<asp:UpdatePanel ID="up_UpdateHeader" runat="server">
<ContentTemplate>
<%--When using "Eval" inside strings for Asp.net controls,
you MUST wrap them in apostrophes ('),
otherwise with (") you will get parser errors!--%>
<asp:LinkButton ID="btn_Header" runat="server"
Text='<%# Eval("HeaderText") %>'
CommandName="UpdatePane" CommandArgument='<%# Eval("ItemID") %>'
Font-Underline="false" ForeColor="Black"
style="width:100%; height:100%; cursor:pointer;"/>
<%--Use Cursor:Pointer to keep a consistent
interface after disabling the button.--%>
</ContentTemplate>
</asp:UpdatePanel>
</HeaderTemplate>
<ContentTemplate>
<asp:UpdatePanel ID="up_UpdateContent" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<%# Eval("ContentText")%>
<asp:Label ID="lbl_Content" runat="server"
Text="<%# DateTime.Now.ToLongTimeString() %>"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
</asp:Accordion>
The Page_Load() - Prep our "dummy" data:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
DataTable dt = new DataTable();
dt.Columns.Add("ItemID");
dt.Columns.Add("HeaderText");
dt.Columns.Add("ContentText");
dt.Rows.Add(new object[] { 123456, "Header 1", "Content A." });
dt.Rows.Add(new object[] { 654321, "Header 2", "Content B." });
acc_Accordion.DataSource = new System.Data.DataTableReader(dt);
acc_Accordion.DataBind();
}
}
The ItemCommand() - This captures button-clicks inside the Accordion:
protected void acc_Accordion_ItemCommand(object sender, CommandEventArgs e)
{
if (e.CommandName == "UpdatePane")
{
AjaxControlToolkit.AccordionContentPanel acp
= (e as AjaxControlToolkit.AccordionCommandEventArgs).Container;
UpdatePanel upHeader
= acc_Accordion.Panes[acp.DisplayIndex].HeaderContainer
.Controls.OfType<Control>()
.Single(c => c is UpdatePanel) as UpdatePanel;
LinkButton btn
= upHeader.ContentTemplateContainer
.Controls.OfType<Control>()
.Single(b => b is LinkButton) as LinkButton;
UpdatePanel upContent
= acc_Accordion.Panes[acp.DisplayIndex].ContentContainer
.Controls.OfType<Control>()
.Single(c => c is UpdatePanel) as UpdatePanel;
Label lbl
= upContent.ContentTemplateContainer
.Controls.OfType<Control>()
.Single(c => c is Label) as Label;
lbl.Text = " ID: " + e.CommandArgument
+ " and Time: " + DateTime.Now.ToLongTimeString();
//You can use the ID from e.CommandArgument to query the database
// for data to update your Repeaters with.
btn.Enabled = false;//Disabling the button for our Header
// will prevent Asyncronous Postbacks to update the content again.
//Only disable this if you don't need to update the content
// when the user clicks to view the pane again.
upContent.Update();//Set UpdateMode="Conditional".
}
}
I know this looks like a lot, but it's only a few lines of code (before wrapping and commenting).
Tip 4 in 6 Tips for Working with the ASP.NET AJAX Accordion Control explains how to determine when the selected index has changed. From the JavaScript event handler you can do whatever you want to update the content of the newly-selected accordion pane (call a web service, use an update panel, etc.)
Combining this with another article explaining how to use an update panel to refesh content when a tab page is selected for a simple demo:
<ajaxToolKit:Accordion ID="accSample" runat="server"
RequireOpenedPane="false" SelectedIndex="-1">
<Panes>
<ajaxToolKit:AccordionPane runat="server">
<Header>Sample</Header>
<Content>
<asp:Button ID="btnSample" runat="server" OnClick="OnShowSample" Style="display: none" />
<script type="text/javascript">
Sys.Application.add_load(function (sender, args) {
if (!args.get_isPartialLoad()) {
var accSample = $find('<%= accSample.ClientID %>_AccordionExtender');
accSample.add_selectedIndexChanged(function (sender, eventArgs) {
$get('<%= btnSample.ClientID %>').click();
});
}
});
</script>
<asp:UpdatePanel ID="upSample" runat="server">
<ContentTemplate>
<asp:DataGrid ID="dgSample" runat="server" Visible="false"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSample" />
</Triggers>
</asp:UpdatePanel>
</Content>
</ajaxToolKit:AccordionPane>
</Panes>
</ajaxToolKit:Accordion>
then in code-behind
protected void OnShowSample(object sender, EventArgs e)
{
dgSample.DataSource = new string[] { "test" };
dgSample.DataBind();
dgSample.Visible = true;
}
Take a look at the ASPxNavBar control (a part of the free ASPxperience Suite) from DevExpress. If the ASPxNavBar’s EnableCallBacks property is set to true, contents of collapsed groups are not represented on the client side. When a group is expanded for the first time, its content is retrieved from the server and then cached on the client. The next time the group is expanded, its content is taken from the client and no callback to the server is performed.
Review the ASPxNavBar - Callbacks (AJAX) Online Demo for more information.
All I can suggest to you is add linkButtons to your headers and panels to your panes:
<Panes>
<asp:AccordionPane ID="First" runat="server">
<Header>
<asp:LinkButton CommandName="ASD2" ID="LinkButton2" runat="server">LinkButton</asp:LinkButton>
</Header>
<Content>
<asp:Panel ID="Panel2" runat="server" Visible="true">
First
</asp:Panel>
</Content>
</asp:AccordionPane>
<asp:AccordionPane ID="Second" runat="server">
<Header>
<asp:LinkButton CommandName="ASD" ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
</Header>
<Content>
<asp:Panel ID="Panel1" runat="server" Visible="false">
Second
</asp:Panel>
</Content>
</asp:AccordionPane>
</Panes>
and in the Accordion1_ItemCommand set the Visible property of corresponding panel.
protected void Accordion1_ItemCommand(object sender, CommandEventArgs e)

ASP.NET - lazy loading dynamic tabs

I'm stumped on this one and hope someone out there's done something similar.
I have an ASP.NET application that has a number of AJAX toolkit tabs. The number of tabs varies page to page, since they're dynamically generated based on settings in a config file.
That being said, some of the tabs are database-driven. The load time when a number of these tabs are on the page can be significant, so I want to implement lazy loading.
I'm following Matt Berseth's pattern, but it seems to break down when the number of tabs is dynamic (each tab needs its own method on the page).
If anyone has a suggestion on how to tackle this, it'd be much appreciated.
I've started working with a small app to get the lazy loading to work. This lazy loads the second tab (which is hard coded), but the third tab is what I'm struggling with (it's dynamically added).
Edited to add code: ASPX page
<script language="javascript" type="text/javascript">
function clientActiveTabChanged(sender, args) {
// see if the table elements for the grids exist yet
var isTab2Loaded = $get('<%= this.lbl2.ClientID %>');
// if the tab does not exist and it is the active tab,
// trigger the async-postback
if (!isTab2Loaded && sender.get_activeTabIndex() == 1) {
// load tab1
__doPostBack('btnTrigger', '');
}
// else if (!isTab2Loaded && sender.get_activeTabIndex() == 2)
// load tab2
// __doPostBack('btnEmployeesTrigger', '');
}
</script>
<asp:scriptmanager ID="Scriptmanager1" runat="server"></asp:scriptmanager>
<div>
<cc1:TabContainer ID="tc1" runat="server" OnClientActiveTabChanged="clientActiveTabChanged">
<cc1:TabPanel TabIndex="0" runat="server" HeaderText="Tab1" ID="Tab1">
<ContentTemplate>
<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
<asp:Label ID="lbl1" text="I am here" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel runat="server" HeaderText="Tab2" ID="Tab2">
<ContentTemplate>
<asp:UpdatePanel ID="up2" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Label ID="lbl2" Text="Load when called" Visible="false" runat="server" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnTrigger" />
</Triggers>
</asp:UpdatePanel>
</ContentTemplate>
</cc1:TabPanel>
</cc1:TabContainer>
</div>
<input ID="btnTrigger" style="display:none;" runat="server" type="button" onserverclick="btnTrigger_Click" />
<input id="btnTrigger2" style="display:none;" runat="server" type="button" onserverclick="btnTrigger2_Click" />
Codebehind:
protected void Page_Init(object sender, EventArgs e)
{
//TabPanel tp = new TabPanel();
//tp.Controls.Add(new LiteralControl("Load first"));
//tp.HeaderText = "Tab1";
//tc1.Tabs.Add(tp);
//tc1.ActiveTabIndex = 0;
//TabPanel tp2 = new TabPanel();
//UpdatePanel up1 = new UpdatePanel();
//up1.Controls.Add(new LiteralControl("Load me when called"));
////up1.Triggers.Add(new AsyncPostBackTrigger());
//AsyncPostBackTrigger trg = new AsyncPostBackTrigger();
//tp2.Controls.Add(up1);
//tp2.Controls.Add(new LiteralControl("Load when called"));
//tp2.HeaderText = "Tab2";
//tc1.Tabs.Add(tp2);
TabPanel tp3 = new TabPanel();
tp3.HeaderText = "Tab3";
UpdatePanel up3 = new UpdatePanel();
LiteralControl lc = new LiteralControl("Load me when needed");
lc.ID = "lit3";
lc.Visible = false;
up3.ContentTemplateContainer.Controls.Add(lc);
tp3.Controls.Add(up3);
tc1.Controls.Add(tp3);
}
protected void btnTrigger_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2500);
this.lbl2.Visible = true;
}
Is the content of the Tabs also database-driven like a CMS?
You could use UserControls as Content and let all implement the same interface f.e. IDataBindable with a function BindData. On this way you can lazyload these UserControl independently of its content.
On ActiveTabChanged you only have to call this function and thenUpdate on the TabContainer's UpdatePanel.
The quick way to do this might be to not load any tabs (i.e. don't actually give them any content) besides the default until that tab is clicked (detected during OnActiveTabChanged or OnClientActiveTabChanged).
However, Tim's method allows the OnActiveTabChanged method to be as simple as databinding the UserControl relative to that tab - that's probably the best method, though it is more effort.

UpdatePanel wrapped around a user control

I have a user control which contains some buttons and a placeholder. Those buttons cause controls to be added/removed from placeholder. Everything works fine.
Now I want to put this user control in a page, and wrap it in an updatepanel like so:
<asp:UpdatePanel ChildrenAsTriggers="true" ID="UpdatePanelFoo" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<grid:tablegrid ID="tablegrid_chapters" runat="server" SomeProperty="bar" />
</ContentTemplate>
</asp:UpdatePanel>
When I run the page, it's still doing a full postback when I hit one of the buttons inside the user control. What am I doing wrong, and how can I remedy this?
Update:
protected void Page_Init()
{
ScriptManager scr = ScriptManager.GetCurrent(this.Page);
Response.Write("EnablePartialRendering: " + scr.EnablePartialRendering);
}
Outputs "EnablePartialRendering: true"
Make sure you have EnablePartialRendering=true on your ScriptManager in the page.
Update
It looks like your UserControl has no events to be looking for...you have 2 options here. Move the UpdatePanel inside the UserControl .ascx so it can see the button events as children to rig up or add an event for it to see, to do that try something like this:
public event EventHandler Click;
void btn_del_Click(object sender, EventArgs e)
{
if (NumberOfRowControls > 0)
{
var rowToWhack = panel_rows.Controls.Children().Single(x => x.ID == "myrow" + (NumberOfRowControls - 1));
panel_rows.Controls.Remove(rowToWhack);
NumberOfRowControls--;
}
if(Click != null) Click(this, e);
}
void btn_add_Click(object sender, EventArgs e)
{
var row = NewRow(NumberOfRowControls);
panel_rows.Controls.Add(row);
if(Click != null) Click(this, e);
}
And update the UpdatePanel to be looking for it:
<asp:UpdatePanel ID="UpdatePanelFoo" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<grid:tablegrid ID="tablegrid_chapters" runat="server" SomeProperty="bar" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tablegrid_chapters" EventName="Click">
</Triggers>
</asp:UpdatePanel>
Make sure you add a ScriptManager as well to the page, otherwise there's no UpdatePanel functionality.

Resources