Showing posts with label update. Show all posts
Showing posts with label update. Show all posts

Wednesday, March 28, 2012

Programmatic refresh of a tab

I have been trawling the forums for a while and still have no solution to my problem. I have multiple tabs each contained within update panels. What i need is for a submit button in one tab to perform the partial update and then programatically update a second tab as well. Any ideas would be greatly appreciated.

ok i finally solved my own problem. I set the updatemode property of the updatepanel to "always". That means that even if another tab is doing an async callback the other tab is always refreshed

Hi i am looking for past one week for tabview form in asp.net 2.0 plz could you help me how to create. i have search i dont have server control in asp.net 2.0. i cant use in my company in AJAX. so, plz let me know as soon as possible.

Thanks

dilip


Hi i am looking for past one week for tabview form in asp.net 2.0 plz could you help me how to create. i have search i dont have server control in asp.net 2.0. i cant use in my company in AJAX. so, plz let me know as soon as possible.

Thanks

dilip


Set UpdateMode="Always" will slow down the page if you have a lots of data on it. If you have many tabs but only want to update one or two of them,why don't try something like:

protectedvoid GridView1_RowUpdated(object sender,GridViewUpdatedEventArgs e)

{

GridView1.DataBind();

GridView2.DataBind(); UpdatePanel2.Update();

}

Programmatical change Label.Text of a set of labels in an UpdatePanel

I write engineering solutions in VB. In most cases they need to operate in both metric and English units of measure so I need to update labels such as °F and °C appropriately. I have a number of labels in an UpdatePanel that need this sort of update. Some need to switch between °F and °C while others betweem feet and meters. Which type of units of measure to use is known at Page_Load so I thought I could just make the Label.IDs meaningful (use lblTemp1, lblTemp2 etc for temperature units) and then update their .Text property based on their ID and the units of measure. I am almost there but I can't seem to gain access to the Text property once I ahve found a Label's whose text I want to change.

Dim iAsInteger = 0

Dim myLabelAs Label

'controls I want to update are in and UpdatePanel...

ForEach ctrlAs ControlIn UpdatePanel1.Controls'check to nake sure it actually has controls first...
If ctrl.HasControls()Then'cycle through all controls in the UpdatePanel...
For i = 1To ctrl.Controls.Count
'if this is a Label then
IfTypeOf ctrl.Controls(i)Is LabelThen
'if the label ID contains "lblTemp this is a temperature unit and must be updatedIf ctrl.Controls(i).ID.ToString.Contains("lblTemp")Then
'HERE IS WHERE THE PROBLEM EXISTS...'can not gain access to the Text property

myLabel =

CType(ctrl, Label)
If uofm = SIUnitsThen 'metric

myLabel.Text =

"°C"Else

myLabel.Text =

"°F"EndIfEndIfEndIfNextEndIfNext

What error do you get? Can you post your ASP.NET code?

What kind of error you are facing ??

Post it here...


The error message I currently get is due to a casting error in the line.Unable to cast object of type 'System.Web.UI.Control' to type 'System.Web.UI.WebControls.Label'.

myLabel =CType(ctrl, Label)

At this point in the code I have found a control and determined that it is in fact a Label who's Text property I need to change. However there is no Text property for the crtl so I am trying to cast the ctrl as a Label.

Jim

Programmatically adding ASP.net User Control to Partial Page Update / UpdatePanel

Hi All, I got a real doozy here. I have read hundreds upon hundreds offorum posts and found numerous others who have replicated this problem,but have yet to find a solution. Through testing I have been able tofind the cause of the problem, and will describe it here firsttextually and then through a code example.

Thepurpose of what I am trying to do is to create a postback-free webapplication through the use of ASP.net AJAX UpdatePanels and UserControls. When programmatically adding a User Control to a web pagethrough a normal postback everything works fine. All the controlswithin the user control are registered properly in the page and anyupdate panels included in the user control also work properly. HOWEVER,if instead of using a full postback you use an UpdatePanel and apartial page update of the UpdatePanel the controls do not getregistered with the page and events from them do not fire (forinstance, a button click event never hits the event breakpoint).

Becausethe very same user control works fine if loaded in a full postback ordynamically added from a namespace works fine, I can be relatively surethat it only is trouble when loading via a partial page update into anUpdatePanel. I load the control via the LoadConrol method and then addit to the page via a PlaceHolder control. Theoretically, adding theUser Control to the PlaceHolder should register itself and it'scontrols and events with the page, but it does not.

Thefollowing code sample is a UpdatePanel-free page using a user controlthat works, later I will show the same code with an UpdatePanel thatdoes not.

I think I need to figure out how to register thecontrols and their events with the page without going through a fullpage postback. Any suggestions??

This example works as expected:
Default.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4<html xmlns="http://www.w3.org/1999/xhtml">
5<head runat="server">
6 <title>Untitled Page</title>
7</head>
8<body>
9 <form id="form1" runat="server">
10 <div>
11 <asp:PlaceHolder ID="UCPlaceHolder" runat="server"></asp:PlaceHolder>
12 </div>
13 </form>
14</body>
15</html>

Default.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10
11public partialclass _Default : System.Web.UI.Page
12{
13protected void Page_Load(object sender, EventArgs e)
14 {
15 Control ctl = LoadControl("~/UserControlDemo.ascx");
16 ctl.ID ="UC1";
17this.UCPlaceHolder.Controls.Add(ctl);
18 }
19}

UserControlDemo.ascx:
1<%@dotnet.itags.org. Control Language="C#" AutoEventWireup="true" CodeFile="UserControlDemo.ascx.cs" Inherits="UserControlDemo" %>
2<asp:Button ID="Button1" runat="server" Text="Display from UC" OnClick="Button1_Click" /> <br />
3<br />
4<asp:Label ID="Content" runat="server" Text="Content"></asp:Label>

UserControlDemo.ascx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12public partialclass UserControlDemo : System.Web.UI.UserControl
13{
14protected void Page_Load(object sender, EventArgs e)
15 {
16 }
17protected void Button1_Click(object sender, EventArgs e)
18 {
19 Content.Text ="Content Changed.";
20 }
21}

Now,consider this variation, where instead of loading the control in thePageLoad event, you do so programmatically via a button Click event.This does not work as it cause a full postback which refreshes theplaceholder. Viewstate does not seem to be working in this case. (usesthe same user control as the previous example)

Default.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4<html xmlns="http://www.w3.org/1999/xhtml">
5<head runat="server">
6 <title>Untitled Page</title>
7</head>
8<body>
9 <form id="form1" runat="server">
10 <div>
11 <asp:Button ID="Button1" runat="server" Text="Load User Control" OnClick="Button1_Click" />
12 <br />
13 <br />
14 <asp:PlaceHolder ID="UCPlaceHolder" runat="server"></asp:PlaceHolder>
15 </div>
16 </form>
17</body>
18</html>

Default.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10
11public partialclass _Default : System.Web.UI.Page
12{
13protected void Page_Load(object sender, EventArgs e)
14 {
15 }
16protected void Button1_Click(object sender, EventArgs e)
17 {
18 Control ctl = LoadControl("~/UserControlDemo.ascx");
19 ctl.ID ="UC1";
20this.UCPlaceHolder.Controls.Add(ctl);
21 }
22}

Tosolve this postback problem, one would naturally want to use anUpdatePanel, like the following example. However this does not work asthe controls do not seem to get registered with the page, and furthernesting of user controls in UpdatePanels (to create a postback freeapp) are no better.

Default2.aspx:

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5<html xmlns="http://www.w3.org/1999/xhtml" >
6<head runat="server">
7 <title>Untitled Page</title>
8</head>
9<body>
10 <form id="form1" runat="server">
11 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
12 <div>
13 <asp:UpdatePanel ID="UpdatePanel2" runat="server">
14 <ContentTemplate>
15 <asp:Button ID="Button1" runat="server" Text="Load User Control into UpdatePanel" OnClick="Button1_Click" />
16 </ContentTemplate>
17 </asp:UpdatePanel>
18 <br />
19 <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
20 <ContentTemplate>
21 <asp:PlaceHolder ID="ContentPlaceHolder" runat="server"></asp:PlaceHolder>
22 </ContentTemplate>
23 <Triggers>
24 <asp:AsyncPostBackTrigger ControlID="Button1" />
25 </Triggers>
26 </asp:UpdatePanel>
27 </div>
28 </form>
29</body>
30</html>

Default2.aspx.cs:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12public partialclass Default2 : System.Web.UI.Page
13{
14protected void Page_Load(object sender, EventArgs e)
15 {
16
17 }
18protected void Button1_Click(object sender, EventArgs e)
19 {
20 Control ctl = LoadControl("~/UserControlDemo.ascx");//loads into the page
21 ctl.ID ="UC1";
22this.ContentPlaceHolder.Controls.Add(ctl);//adds to page control tree (or at least it should)
23 }
24}

I knowI can use the "visible" property of my controls to toggle them on andoff a page to create a flicker free experience, however, my applicationis a database intensive app and I don't want the page running queriesagainst the database unless I'm absolutely sure the user wants them.Rendering a 10 forms and keeping them hidden isn't a big deal, butrunning 10 queries that the user never wants to see is, otherwise I'dstick to that method, its works perfectly. Any suggestions? Or requestsfor clarification? Any help you can provide is muchappreciated...thanks, Chris.

My suggestion is to not use an updatepanel for this. Google for ScottGu's blog on templating tricks; you can use a service to grab an ascx, feed it a datasource to populate the data then send the results to the page. use javascript to insert those results into the page DOM where needed, and code all your functionality in js or web methods of one form or another. It's a much cleaner / lower overhead way to do what you're trying to do anyway.


Hi Paul, I took a look at ScottGu blog, I believe this is the article you were referencing: http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx

Unfortunately this is not the solution I am looking for. By using this method I lose the main benefits of ASP.net: managed code, event based triggers, and the rest of the integrated features. I believe this method will cause the same problem, whatever I load into the page, the page won't be aware of it and no events will fire.

For now I am going to have to use postbacks, and I'll used the update panels for keeping things like sorting gridviews postback-less.

Thanks for the suggestion though!


I am having exactly the same problem

Can someone please help?

In similar situations before, I have used javascript and other hacks, but I feel reluctant to try to do it again. If we have a framework that can be used and can make work simpler, then It makes sense.

However, these kind of problems are frustrating, and I don't know what is the resolution. I am sure people mus thave encountered this before.

Can someone help?


This is more a dynamic controls problem than an AJAX problem.

When you dynamically add a control, you have to add it EVERY request. By moving it from PageLoad to Button_Click, you've stopped creating the control every request. You only create it if the button is pressed. That is why the events won't fire when you use controls within the user control -- because on the postback, the control doesn't even exist! The postback data is for a control that isn't in the control tree, because you didn't add it, because the event that adds it isn't firing again.

The technique to solve this is to utilize viewstate to remember that the control has been added, so that you can add it from the LoadViewState method. In your click handler, call a new method - LoadUserControl(). Define LoadUserControl to create and add the control, and to set a viewstate key, ViewState["LoadUserControl"] = true. Then override LoadViewState, and after calling base.LoadViewState, look for that viewstate key. If its true, call LoadUserControl().

New problem... Now its possible it will be added twice -- if you click the same button a 2nd time, LoadViewState will call it, and so will your button click handler. So add code to your button click handler to avoid creating it if its already loaded -- just check for the viewstate key.


Infinities...This is very interesting, thank you for your response! Unfortunately you lose me when you talk about overriding the LoadViewState. How would you modify the following code to accomplish what you are saying?

protected void Button_Click(object sender, EventArgs e)
{
Control ctl = LoadControl("~/userControl.ascx");
this.Panel1.Controls.Add(ctl);
}
Thanks!

Ok, that sounds promising. But, I don't think the situation would work still.

I have a gridView. In every row of a gridview, one of the cells contains a nested update panel. When the user clicks on a particular row, a user control dynamically gets added to the nested update panel. This works fine.

When I click on a particular button INSIDE this user control then the postback disappears, no events are triggered and nothing happens. The fact that the control probably does not exist makes sense because it justifies what happens, as in no events are fired.

However now this user control has values and data inside it, so when you are saying to load that control again, what happens to the value and the data, it looks like that data is lost. Is that not right?

Basically, in my situation AJAX cannot help. In the first place my user control should already have a viewstate in order to persist the value of data and state of the elements inside the user control. Since its viewstate is not stored, the "re-adding" will simply not work at all.


gsinha25:

However now this user control has values and data inside it, so when you are saying to load that control again, what happens to the value and the data, it looks like that data is lost. Is that not right?

No that is not right. The fact you are loading it again doesn't mean its data is lost. All controls are reloaded every request, even the statically declared ones. ViewState maintains itself through the framework, but it only maintains the data in the control, not the control itself.

gsinha25:

Basically, in my situation AJAX cannot help.

You would have the same problem if you were not using ajax. What you'd see is that the loaded user control would disappear after you click a button in it.

gsinha25:

In the first place my user control should already have a viewstate in order to persist the value of data and state of the elements inside the user control. Since its viewstate is not stored, the "re-adding" will simply not work at all.

ViewState is maintained for the control. All you have to do is make sure it exists every request. It will work, trust me.


I'm sure the formatting of this is going to be off, but here's the basic idea.

protected void Button_Click(object sender, EventArgs e)
{
LoadUserControl();
}
private void LoadUserControl()
{
Control ctl = LoadControl("~/userControl.ascx");
this.Panel1.Controls.Clear();
this.Panel1.Controls.Add(ctl);

 ViewState["Loaded"] = true;

}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);

 if (ViewState["Loaded"] != null)
LoadUserControl();
 }


Hi Infinities,

This is starting to make sense. I believe what you are talking about will work for my problem - in fact I often assumed it had something to do with the viewstate, however my knowledge and experience with it is limited. (I am new to C# and ASP.net, coming over from ColdFusion.) I am still a little confused on the the LoadViewState override. As I understand it, this event fires after the Init event in the lifecyle, and it's goal is to reload the user control if it has been added to the page. One question that pops up here, and may be what gsinha was referencing, does chages to the control also progress if it is reloading the control every time? For instance, if the user control is a gridview populated from a database and I have sorted and/or filtered it, would these sorts and filters be passed along as well?

Another question, when you assign the view state key in "ViewState[" "] = true" does it matter which key you use? And a final question, where is the savedState object coming from in the LoadViewState override?

Thanks again for your help!

P.S. I read your writeup at your website on the viewstate, I think i'll need to read it three or four more times before I can make sense of it all but amazing stuff, I love the attention to detail!


ChrisCicc:

As I understand it, this event fires after the Init event in the lifecyle, and it's goal is to reload the user control if it has been added to the page.

The general role of LoadViewState is to deserialize the control's share of the page's entire viewstate payload. Think of viewstate as just a bunch of data -- data which is associated with each control on the page. On a postback, that data is available to the control that owns it again, if it's still around that is. The role of the code I gave you is to recreate the control if it was remembered previously that it had been created.

ChrisCicc:

One question that pops up here, and may be what gsinha was referencing, does chages to the control also progress if it is reloading the control every time? For instance, if the user control is a gridview populated from a database and I have sorted and/or filtered it, would these sorts and filters be passed along as well?

Yes -- because what you have to understand is that all controls are reloaded every request. In fact, the page is completely reconstructed from the ground up every request. Remember request/response mechanism of the web is essentially a stateless process. ASP.NET and other frameworks create the feeling of statefulness through tricks like ViewState and Session state. ViewState is persisted across posts -- the controls are not. You create the control tree for the page by either statically declaring it with asp.net markup, or by dynamically creating the controls yourself. But either way, the controls start completely fresh and new every request. ViewState is then deserialized and injected into the controls, restoring them to the state they were on the last request.

ChrisCicc:

Another question, when you assign the view state key in "ViewState[" "] = true" does it matter which key you use?

No -- the idea is just to remember the fact that the control was loaded. Each control's viewstate is scoped to it, so there's no risk of using a key thats already in use by some other control.

ChrisCicc:

And a final question, where is the savedState object coming from in the LoadViewState override?

That is the deserialized viewstate associated with that specific control. The base implementation uses it to repopulate the keys stored in the ViewState statebag.


ChrisCicc:

P.S. I read your writeup at your website on the viewstate, I think i'll need to read it three or four more times before I can make sense of it all but amazing stuff, I love the attention to detail!

Thanks for reading :) I know it's quite long... but hopefully worth it.


It works!! Thanks a bundle! This solved the most important problem I had, which was loading the user control on to the page via an Update Panel. It does however bring up a few further questions that I was hoping you could help with!

First, how do I modify your code so that I can have multiple buttons load different UCs each while still using the LoadViewState override? The following code is my best attempt at it:

Instead of using the click event to call the LoadUserControl function, I did this:

  
protected void LinkButton_Click(object sender, EventArgs e)
{
MainBodyPanel.Controls.Clear();
Control ctl = LoadControl("UserControl.ascx");
MainBodyPanel.Controls.Add(ctl);

ViewState["Loaded"] =true;
}

And then in the override I did as you suggested, only added an addtional If statement for each button and control,
and sent it back to the click event function instead of the LoadUserControl so that each control could have its
own viewstate key.
While I can add new controls to the page, I cannot see them again once another control calls the .clear()
function an all that is left is the viewstate which then throws an error as it doesn't see the same control tree.
Is there a better way?
 
The second problem I have is I cannot get different user controls to communicate with each other. This is
apparent in two places. The first is I have a user control with a set of links. it is these links that call the
other user controls into the update panel dynamically. If I add the UserControl dynamically before the page
loads, the links can't see the container panel on the page. I tried using this.findControl("...").Controls.Add()
but that didn't work. So for now I have the links hard coded into the page instead being their own user control,
but it's really too complex to keep doing it that way, and it limits my nesting options.
Thanks again for any help u can provide! 
 

Ok... help me understand :) You have a bunch of links, which when one is clicked, you want to dynamically load a user control into a particular spot. Is that 'spot' different for each link? If you click on one link and then another are there supposed to now be 2 controls on the page or does the 2nd one replace the first?

I'll assume you want only 1 control at a time.

What you described sounds like it should work. I personally wouldn't explicitly call the event handler -- thats usually a bad idea. It won't cause any problems if you know what you're doing but its better design to have a 3rd method that they both call, which gives each method a clear distinct purpose (its generally bad if you have to think... who called this method?).

One think you should definitely do is give the User Control you load a particular ID. Make the ID based on something that will (1) be exactly the same every time and (2) be different for different user controls. So for example, clicking on Link1 might load UC1.ascx with ID "uc1", and clicking Link2 might load UC2.ascx with ID "uc2". The reason for this is.. well, when you dont specify an ID, any control that requires one (textboxes for example) will use an autogenerated one. But if you load controls differently on a postback than you did on the first request, the IDs wont necessarily be the same, causing problems. Assigning an ID avoids that. You shouldn't have been getting the exception you mentioned... try what I said and let me know. If you still get it, show me some code...

About your user control communication problem... I'm not following 100%. Where and when exactly are you calling FindControl, and what control are you trying to find? With controls whenever you find yourself trying to get two of them to talk directly to each other... well its usually a sign that you could improve your design a bit. The control should be self sufficient, it shouldn't be broken because something else on the page isnt just so. Rather than have the control talk to the other control, you can have it raise an event. The page then listens for the event and decides what to do with it (something which the original control doesn't much care about), which may be to push something into another control on the page (the origin of which that control doesn't much care about). Much less coupled that way.


"I'll assume you want only 1 control at a time." correct assumption. there is a panel placeholder that the controls get swapped in and out of.

I tried adding the ID as you suggested but the exception still came up. Here is the code as it currently stands:

1protected void ViewCustomerListLinkButton_Click(object sender, EventArgs e)2 {3 MainBodyPanel.Controls.Clear();4 Control ctl = LoadControl("~/UserControls/CustomersControls/CustomerList.ascx");5 ctl.ID ="CustList";6 MainBodyPanel.Controls.Add(ctl);78 ViewState["CustList"] =true;9 }1011protected void AddCustomerLinkButton_Click(object sender, EventArgs e)12 {13 MainBodyPanel.Controls.Clear();14 Control ctl = LoadControl("~/UserControls/CustomersControls/CustomerAdd.ascx");15 ctl.ID ="CustAdd";16 MainBodyPanel.Controls.Add(ctl);1718 ViewState["CustAdd"] =true;19 }2021protected override void LoadViewState(object savedState)22 {23base.LoadViewState(savedState);2425if (ViewState["CustList"] !=null)26 ViewCustomerListLinkButton_Click(null,null);2728if (ViewState["CustAdd"] !=null)29 ViewCustomerListLinkButton_Click(null,null);3031 }

The exception is thrown because when I click on a second link, it Clears the MainBodyPanel control list, and the viewstate is looking for the control list that includes the now removed control. I tried various ways I could think of to remove the viewstate but to no avail...

"What you described sounds like it should work. I personally wouldn'texplicitly call the event handler -- thats usually a bad idea. It won'tcause any problems if you know what you're doing but its better designto have a 3rd method that they both call, which gives each method aclear distinct purpose (its generally bad if you have to think... whocalled this method?)."

I couldn't figure out a way to do this. I was having each click event pass the url via the function call LoadUserControl("~/control.ascx") but I couldn't figure out how to have the loadviewstate override pass the url back when needed, so I did it as you see above.

About the communication problem, in more detail, the problem is actually with the code above. Right now that is in my pages code behind, if i make those links into a user control, and then add the control to the page with those functions in the controls code behind, it cannot see the container panel (which in this case is the MainBodyPanel). I tried using the find control method but it still couldn't see it. With the links and event handlers hard coded it works fine.

Thanks!


With this code, once you click on one of the buttons, that control will always be loaded. When you click on one button you need to 'clear' the viewstate key of the other, otherwise you'll be trying to load both controls all the time. Pretty sure that is why you are getting the error, too. Easier if you just use the same key with a different value.

About the event handler thing...

protected void Link1_Handler(object sender, EventArgs args) { Foo(); }
private void Foo() { /* load Foo, set ViewState["Loaded"] = 1 */ };

protected void Link2_Handler(object sender, EventArgs args) { Bar(); }
private void Bar() { /* load Bar, set ViewState["Loaded"] = 2 */ };

protected override void LoadViewState(object savedState) {
base.LoadViewState(savedState);

if(ViewState["Loaded"] == 1) {
Foo();
}
else if(ViewState["Loaded"] == 2) {
Bar();
}
}

You might be tempted to store the path to the actual UserControl in ViewState, that way you can just LoadControl(ViewState["Loaded"]) ... but, don't :) Treat ViewState like user input. Don't trust it. If you did it that way, the user could maniuplate viewstate in such a way that they could cause any user control in your site to load, rather than be restricted to the two you want.

Ok... so I'm still confused about your links problem. You have each link as a user control, and when clicked you want them to load their content into the parent? Controls should not modify their parent's controls. It would be better like I said, to have an event raised by the control. The page, which contains all these link controls, just hooks that event on each control and then loads the control into the appropriate place. Your FindControl probably isn't working because FindControl only finds controls within the current naming container. User controls are naming containers. So when you say, this.FindControl("foo") from within a UserControl, you're only looking for a control named "foo" WITHIN the user control, not higher. To go higher you have to call FindControl on a control thats higher. But you still have to be careful with naming containers. You could start at the page level with this.Page.FindControl("foo"), but that will only find controls named "foo" that are children of page or children of non-naming containers in page. Imagine if you had a user control that contained control with ID "foo", and then you put 5 of them on the page. Which would you expect Page.FindControl("foo") to find? Its ambiguous -- thats why it won't find ANY. Each Foo is within a naming container, so their actual IDs are "uc1$foo", "uc2$foo", etc (where uc1=id of user control 1). If you know for sure the control will be in a particular place (for you it sounds like in a master page), then go ahead and hard code that ID... but be warned, its a fragile way to do it. Another approach is to have your Page expose a "MasterContainer" property of type Control. The user controls can then just say ((MyPageType)this.Page).MasterContainer.Controls.Add(), and it will work so long as the control is on a page that inherits from "MyPage" (which, all of your pages could inherit from).Ad infinitum... lots of different ways to deal with it.

programmatically checking atlas update progress

Hi,

I was wondering if there's a way to check the status of atlas update panel through script? I want to write some scripts after the update panel complete its process of getting data from the server.

Thanks.

hello.

well, you can do that easilly by handling the propertychanged event of the _pagerequestmanager object. search this forum for _pageRequestManager and _inPostBack. you'll find 1 or 2 posts on how to do that (from xml-script and javascript).


Thanks Luis. I found my answer in one of the posts.

Monday, March 26, 2012

Progress bar appear when submiting form

I have a contact us form that sends an email.

I want to use an update panel which allows me to do the following:

When the user clicks the send button, form dissapear and progress bar is show for a couple seconds and then notification to the user if email sent ok or not.

I have implemented this using updatepanel and updateprogress but 99% of the time the updateprogress is not displayed because the command is carried out so quick. I would like the progress bar be displayed and give the user the feel of the email being sent. I have the form in a standard panel. How can i make sure the form disappear and updateprogress is displayed?

I have looked at using the updatepanelanimator but it seems difficult to use and think i can do what i want to do without it, correct?

Appreciate any help.

You could approach this a number of ways.. here is probably the quickest and dirtiest way but I don't recommend it:

Add:

System.Threading.

Thread.Sleep(2000);

To your server side processing, this will block the current thread for a specific number of milliseconds forcing the browser and UpdateProgress to wait for the response. Please don't do this. :)

A better way to do this would be to use an animation sequence to give the user the visual feedback that something has taken place, in this case that an email has been sent. The ASP.NET Ajax Animation Toolkit works excellent for this because you can specify the duration for which animations will run... so even if your UpdateProgress and UpdatePanel have completed processing, you could still have an animation still playing before the user moves on to a new action.

Try the animation framework, it's quick to pickup and has some very nice tutorials:http://ajax.asp.net/ajaxtoolkit/Walkthrough/UsingAnimations.aspx

Cheers,
Al

Progress template not showing

I got an updatepanle, an updateprogress , a label inside the update panel, and a button outside the updatepanel, what i wanna do is just simple, delay 5 sec before showing the label and at the same time showing the "loading..." before it complete. Problem occured when i put the button outiside of the updatepanel and it did not show the "loading.." and after 5 sec the label will shown , but everything works fine when i put the button in the updatepanel...I did set the button as trigger.

so may i know where is the problem ?

Thanx~

Hi giox,

Posting the code of your page would help us in locating the eventual problem.

Would you be so kind to use the Source Code button of the rich editor to insert code? TNX!

Kind regards,
Wim


i dont believe you need to set the button as a trigger if its in the update panel, also, have you tried setting the update progress "DisplayAfter" property to "0"?


Wim,

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lbl1" runat="server" Style="left: 48px; top: 0px" Text="Label" Width="352px"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
</div>

<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1" DisplayAfter="0">
<ProgressTemplate>
loading..
</ProgressTemplate>
</asp:UpdateProgress>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</form>

VB code :

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
System.Threading.Thread.Sleep(3000)
Me.lbl1.Text = "abc"
End Sub

Thanx~


Lee Brennan:

i dont believe you need to set the button as a trigger if its in the update panel, also, have you tried setting the update progress "DisplayAfter" property to "0"?

The problem occured when the button is outside the update panel..

I tried to set "DisplayAfter" property to "0", but it still not working. thanx anyway.


The documentation is the problem on this one. If you look at the AssocitatedUpdatePanelID attribute, it states "You can set theAssociatedUpdatePanelID property to controls in the same naming container, a parent naming container, or the page."

What exactly that means is certainly not clear, because it does not work if it is used as a sibling of the UpdatePanel. (and you would think that that's what "in the same naming container" means)

If you delete the AssociatedUpdatePanelID completely, your example will work.

Of if you move the UpdateProgress "as is" inside the UpdatePanel, it will also work.


If want to show the UpdateProgress for a control which is outside the UpdatePanel you have to manually hook the initializeRequest and endRequest of PageRequestManager to show the UpdateProgress, like the following:

<script type="text/javascript"> var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_initializeRequest(initializeRequest); prm.add_endRequest(endRequest); var _postBackElement; function initializeRequest(sender, e) { if (prm.get_isInAsyncPostBack()) { e.set_cancel(true); } _postBackElement = e.get_postBackElement(); if (_postBackElement.id.indexOf('Button1') > -1) { $get('UpdateProgress1').style.display = 'block'; } } function endRequest(sender, e) { if (_postBackElement.id.indexOf('Button1') > -1) { $get('UpdateProgress1').style.display = 'none'; } }</script>

While I use the technique above as well for most projects, it is not necessary in this example. Simply eliminating the AssociatedUpdatePanelID attribute on the ProgressPanel will allow the example to work. That occurs because Button1 is also defined as a trigger for the panel. What was confusing is why it doesn't work with the attribute set because that is not clear from the documentation for the AssociatedUpdatePanelID attribute.

When reading the documentation for the UpdateProgress, none the scenarios described include the way the example was initially written. Only when the attribute is deleted does the following statement (bold type) apply:

"If you do not set theAssociatedUpdatePanelID property, theUpdateProgress control displays progress for any asynchronous postback that originates from inside anyUpdatePanelor for controls that are triggers for panels."


wrayx1:

While I use the technique above as well for most projects, it is not necessary in this example. Simply eliminating the AssociatedUpdatePanelID attribute on the ProgressPanel will allow the example to work. That occurs because Button1 is also defined as a trigger for the panel. What was confusing is why it doesn't work with the attribute set because that is not clear from the documentation for the AssociatedUpdatePanelID attribute.

It works when eliminating the AssociatedUpdatePanelID ...Thanx..the problem has solved, thanx to those who helping to solve this problem as well.

Providing Scroll Bars to update panel

Hi,
I am using ajax for loading different user controls . I have two main problems
1. I have a main page where i have 4 update panels . the structure is like the the following( i removed the atributes for each elemnet like id , runat etc
<table>
<tr>
<td><updatepanel><contenttemplate><uc1:ststicbar><ontenttemplate></updatepanel><td>
<td><updatepanel><contenttemplate><uc1:dynbar><ontenttemplate></updatepanel><td>
</tr>
<tr>
<td colspan=2><updatepanel><contenttemplate>content here<ontenttemplate></updatepanel></td>
</tr>
<tr>
<td colspan=2><updatepanel><contenttemplate><uc1:statusbar><contenttemplate></updatepanel><td>

</tr>
</table>

where i have two user controls on top
and one at the bottom representing toobars and ststus bar(bottom)
in the middle update panel i am loading different user controls.
my problems are.

1. I need the keep the top toolbars and bottom status bar always visible
ie when i load a user control in the midddle update panel if its height is more there should be a scroll bar
I tried with adiv tag for the content but not worked properly i find update panels emit div tag in the client.
is there any way to provide scrolling for the update panel.ie the div tag which is get emitted for the update panel.

Thanks and Regards
Jereesh

All the Style Tag works also with the table tr and td tag

apply ur style to the Table like

<table id=tbl1 style="OVERFLOW:auto;WIDTH:200px;HEIGHT:230px;">

<tr><td></td></tr>

</table>

It will sork fine iam using it.

any proble get back to me.


Hey,

Just put the update panel for which you wanna have the scrollbars, inside a panel saypanel1.

Set the height and width of the panel and set the scrollbar property of the panel as you like.

publish ajax website

Hi,

I am beginner with Ajax and I have done an app using some update panels and triggers but before I upload the app to the server I wanted to know if I have to do something on the server so the app will run without any problem.


1. I am not using any ajax control, only updates panel.

2. Do have to configure something?

3. Can I just publish the site and then upload it?

Can any body explain me something about it or maybe give me an URL where i can found some info.

Thanks a lot.


Just install the asp.net ajax framework on you server then you're good to go.

Thanks for your answer.

But it is a remote server so I do not think I have permissions to install the ajax framework. Or I have to tell my provider that I want that framework?

Thanks again.


hmmm hosting provider? Ask them, ... to do install it ... if they don't then transfer somewhere else. .. i'm with GoDaddy, and they have it ... the price is cheap too. if you do go with GoDaddy, check around for promotion code. i have one ... let me know if you need it ... Cheer.

I just talked to my provider and they do not have the ajax framework and the person that I working for does not want to change the provider. I know, I had to ask this person about this before I started....... there′s no way to run an app which has ajax without the Ajax Framework? I am just using update panels and triggers and no ajax controls.

Thanks a lot.


You can try putting the DLLs in the bin folder like the old "Atlas", but then your folder has to have full permission. AND for sure your provider will not give it to you.

i did try putting all the DLLs in the bin folder on my hosting provider (godaddy) when they didn't have ajax install. the result was, it blows up on me. yellow page. 'sigh' ...

who is your provider?


my provider is 1&1......why do I need full permission to put some dll in my projects?

Look I have all the Data access and the business logic in different projects. That means that in the client side I use the dll from those projects.

Do I need also full permissions to use these dll's in my project?

Or do I have to upload those project to server too?

Tanks a lot.

Saturday, March 24, 2012

Pulling hair out! Cannot get GridView & Search Button to work with Update Panel

I don't know what else to do. As far as I know, my web.config is set up fine. I get no errors as to the ASP.NET AJAX controls and I feel I have tried everything I know, which isn't much yet about UpdatePanels but there doesn't seem to be that much to know after reading

Here's my code below. When I click the search button, I still am getting a full page postback:

<formid="Form1"runat="server"method="post">

<asp:scriptmanagerid="ScriptManager1"enablepartialrendering="true"runat="server"/>

...more code and then

<tdclass="narrowTableWrapperCell"colspan="8"align="left">

<asp:updatepanelid="gvSearchResultsUpdatePanel"runat="server"updatemode="always">

<contenttemplate>

<asp:updateprogressid="UpdateProgressSearchResults"runat="server">

<progresstemplate>

Working......

</progresstemplate>

</asp:updateprogress>

<asp:buttonid="Search"runat="server"onclick="Search_Click"usesubmitbehavior="false"width="113px"/>

<asp:gridviewid="SearchResults"runat="server"onpageindexchanging="SearchResults_PageIndexChanging"onrowcreated="SearchResults_OnRowCreated"

onsorting="SearchResults_Sorting">

<columns>

<asp:templatefielditemstyle-horizontalalign="left">

<headertemplate>

<asp:checkboxid="cbSelectAll"runat="server"textalign="left"/>

</headertemplate>

<itemtemplate>

<asp:checkboxid="cbRow"runat="server"/>

<asp:hyperlinkid="hyName"runat="server"navigateurl='<%# FormatUrl(Eval("MyID"))%>'text='<%# Eval("FullName")%>'/>

</itemtemplate>

</asp:templatefield>

<asp:boundfielddatafield="Phone"headertext="Phone"htmlencode="False"itemstyle-horizontalalign="left"readonly="True"sortexpression="Phone"/>

<asp:boundfielddatafield="HomePhone"headertext="Other Phone"htmlencode="False"itemstyle-horizontalalign="left"readonly="True"sortexpression="HomePhone"/>

<asp:boundfielddatafield="Email"headertext="Email"htmlencode="False"itemstyle-horizontalalign="left"readonly="True"sortexpression="Email"/>

<asp:boundfielddatafield="AlternateEmail"headertext="Alt Email"htmlencode="False"itemstyle-horizontalalign="left"readonly="True"sortexpression="AlternateEmail"/>

<asp:boundfielddatafield="PrimaryAddress"headertext="Primary Address"htmlencode="False"itemstyle-horizontalalign="left"readonly="True"sortexpression="PrimaryAddress"/>

<asp:boundfielddatafield="ShippingAddress"headertext="Shipping Address"htmlencode="False"itemstyle-horizontalalign="left"readonly="True"sortexpression="ShippingAddress"/>

</columns>

</asp:gridview>

</contenttemplate>

</asp:updatepanel>

</td>

...rest of aspx

My Webconfig:

<?xmlversion="1.0"?>

<configuration>

<!-- ASP.NET AJAX Settings | Do not remove-->

<sectionGroupname="system.web.extensions"type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

<sectionGroupname="scripting"type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

<sectionname="scriptResourceHandler"type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"requirePermission="false"allowDefinition="MachineToApplication"/>

<sectionGroupname="webServices"type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

<sectionname="jsonSerialization"type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"requirePermission="false"allowDefinition="Everywhere" />

<sectionname="profileService"type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"requirePermission="false"allowDefinition="MachineToApplication" />

<sectionname="authenticationService"type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"requirePermission="false"allowDefinition="MachineToApplication" />

</sectionGroup>

</sectionGroup>

</sectionGroup>

<!-- End ASP.NET AJAX Settings-->

</configSections>

<system.web>

<!-- ASP.NET AJAX Settings | Do not remove-->

<pages>

<controls>

<addtagPrefix="asp"namespace="System.Web.UI"assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<addtagPrefix="asp"namespace="System.Web.UI.Controls"assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<addtagPrefix="ajaxToolkit"namespace="AjaxControlToolkit"assembly="AjaxControlToolkit"/>

<addtagPrefix="iu"tagName="Footer"src="~/Components/Footer.ascx" />

<addtagPrefix="iu"tagName="Header"src="~/Components/header.ascx" />

<addtagPrefix="iu"tagName="Navbar"src="~/navbar.ascx" />

</controls>

</pages>

<compilationdebug="true">

<assemblies>

<addassembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

</assemblies>

</compilation>

<!-- End ASP.NET AJAX Settings-->

<httpHandlers>

<!-- ASP.NET AJAX Settings | Do not remove-->

<removeverb="*"path="*.asmx"/>

<addverb="*"path="*.asmx"validate="false"type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<addverb="*"path="*_AppService.axd"validate="false"type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<addverb="GET,HEAD"path="ScriptResource.axd"type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"validate="false"/>

<!-- End ASP.NET AJAX Settings-->

<addpath="ChartAxd.axd"verb="*"type="Dundas.Charting.WebControl.ChartHttpHandler"validate="false" />

</httpHandlers>

<!-- ASP.NET AJAX Settings | Do not remove-->

<httpModules>

<addname="ScriptModule"type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

</httpModules>

<!-- End ASP.NET AJAX Settings-->

<xhtmlConformancemode="Legacy"/>

</system.web>

<!-- ASP.NET AJAX Settings | Do not remove-->

<system.web.extensions>

<scripting>

<webServices>

<!-- Uncomment this line to customize maxJsonLength and add a custom converter-->

<!--

<jsonSerialization maxJsonLength="500">

<converters>

<add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>

</converters>

</jsonSerialization>

-->

<!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate.-->

<!--

<authenticationService enabled="true" requireSSL = "true|false"/>

-->

<!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved

and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and

writeAccessProperties attributes.-->

<!--

<profileService enabled="true"

readAccessProperties="propertyname1,propertyname2"

writeAccessProperties="propertyname1,propertyname2" />

-->

</webServices>

<!--

<scriptResourceHandler enableCompression="true" enableCaching="true" />

-->

</scripting>

</system.web.extensions>

<!-- End ASP.NET AJAX Settings-->

</configuration>

You forgot to add triggers. See the other post you sumited on this subject. I gave you an example code for you to use.

push data to client/ keep checking the server side for any update to load

hi..

Im developing a web application to be used over the internet (not entranet) that means I have unknown of users accessing my web site.

I need to keep checking the server side every 30sec by creating hidden iframe to keep submiting to the server and check for specific updates( such database table). I think this way will reduce the performance of the server and not accepted!

is it true as I think? there is any other technique to this? is there some AJAX control to use instead?

note: Im fetching a small amount of text from the server

It really depends on your system and the expected number of users. Of course, every time you poll the server it takes some performance but in many cases the rewards outweight the performance hit.There are a lot of sites that do this and its not a huge performance hit if you are just retrieving a small amount of text. I would say go for it if you have the capacity.


Take a look at this: http://encosia.com/index.php/2007/07/25/display-data-updates-in-real-time-with-ajax/

The page method call for polling keeps the traffic level very low, compared to other techniques.

Question about atlas and web interface update

Is the following scenario possible with atlas:

A web based application is run on a server, so clients use web browser to access it. The application uses inforamation from a database to populate the UI with the information. The information is stored in a database and can be changed either from the application or some other source (lets say another server). Is is possible to update the UI on a user's computer when the database is updated from the other server (the user doesn't need to refresh the screen manualy)?

Thanks in advance,
Marko Vuksanovic.

hello.

well, it's possible, though probably not as you wanted. what you must do is poll the server from the client from x to x seconds and if there's new info, then refresh the client. the most common approach is:

1- wrap the contents that need to be refreshed with an updatepanel

2- call the web service from x to x seconds; if there's new info, then refresh the panel.

Wednesday, March 21, 2012

Question about updatepanel

Hi,
I got a problem about update panel.
My scenario is that:
I have two tasks, each of which is triggered by buttons..
"A" needs 10 seconds to complete, and "B" needs 2 seconds.
After clicking A button, the user click B within 10 seconds.
Normally the program will stop doing A and start doing B, right?
But once I use the UpdatePanel, it just keep doing A and doesn't do B.
WHY?

Here is my example code:

<body> <form id="form1" runat="server"> <atlas:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="True"/> <asp:Button ID="ButtonA" runat="server" Text="intensive task" /> <asp:Button ID="ButtonB" runat="server" Text="interrupt task" />  <asp:Label ID="Label2" runat="server" /> <atlas:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Label ID="Label1" runat="server" /l> </ContentTemplate> <Triggers> <atlas:ControlEventTrigger ControlID="ButtonA" EventName="Click" /> </Triggers> </atlas:UpdatePanel> <atlas:UpdateProgress ID="UpdateProgress1" runat="server"> <ProgressTemplate> Processing... </ProgressTemplate> </atlas:UpdateProgress> </form> </body>
Protected Sub ButtonA_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles ButtonA.Click System.Threading.Thread.Sleep(10000) Label1.Text ="Intensive task suceeded!!"End Sub Protected Sub ButtonB_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles ButtonB.Click Label2.Text ="Interrupted task succeeded!!"End Sub
I need the normal function, that is to stop A and do B when clicking ButtonB, and also the function of partial refreshing. Any ideas?Could anyone give me some suggestion?

Question about using AJAX to update a GridView

I'm pretty new to AJAX, but so far I have managed to get a web page working that calls a web service, and the web service returns an array of objects. I would like to use those objects to populate a GridView. But so far, I have been unable to find a way to do that from the javascript on the page. Is this possible?

Hi Ian,

The Microsoft GridView does not have that ability currently. If you're interested, there are other 3rd party grids out there that currently provide a client-side model for adding rows.

-Tony


hi Ian,

did you tried to use ObjectDataSource? take a look at it this linkhttp://www.gridviewguy.com/ArticleDetails.aspx?articleID=139 may be helpful to you.

regards,

satish.


OK, since there's no easy way to do this now, and I don't have the budget for a pre-packaged control, I just did it manually with good old HTML tables and javascript. Thanks for the help though.

Question about: A demonstration of ASP.NET AJAX

I have just whatchedA demonstration of ASP.NET AJAX @dotnet.itags.org. http://ajax.asp.net/

and i notice that during the demon the demonstrator creates two update pannels the one containing the data list the other containing the insert record control, what is not clear from this demo is weather the it is posible to update the datalist now that the insert record control is in a seperate update panel, as no extra triggers were added to the data list. Being a synic i wondered if the demonstrator had deiberatley paged the data list and added extra items to it before the update pannels were introduced so that when he added the extra record via the control in the update pannel it would be added to the end of the list, which was on the secound page which could only be viewed when the user selected to view the secound page forcing the datalist update panel to be refreshed. So i was left wondering if this was to hide a limmitation of the technology and weather it was posible to add a asychronus post back triger based on the event that is within a seperate update pannel.

Q. Is it posible to add a asychronus post back triger, in one update pannel based on the event of a control in a diferent (sibling) update pannel, is that control visible from the other update pannel?

ps Any change of a spell check for this interface, i think i could use oneWink

The answer is yes. Here is a simple example:

1<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">2 <ContentTemplate>3 <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">4 <asp:ListItem Text="CA" Value="CA" />5 <asp:ListItem Text="CO" Value="CO" />6 <asp:ListItem Text="FL" Value="FL" />7 </asp:DropDownList>8 </ContentTemplate>9</asp:UpdatePanel>1011<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">12 <ContentTemplate>13 Last Update:<%= DateTime.Now.ToLongTimeString()%>14 </ContentTemplate>15 <Triggers>16 <asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged" />17 </Triggers>18</asp:UpdatePanel>

In line number 16 you can see that a trigger is registered for a control that reside within a different UpdatePanel. Also, programmatically you can also call the Update() method on any UpdatePanel that has it's UpdateMode set to Conditional.

Question re default button inside an update panel not working

I have a page containing an update panel. Inside the update panel are two user controls: one that displays messages, and one that allows message capture.
The message-capture control looks like this:


<asp:Panel ID="PanelChatSay" runat="server" DefaultButton="ButtonSay" >
<asp:TextBox ID="TextBoxChat" runat="server" Width="90%"/>
<asp:Button ID="ButtonSay" runat="server" Text="Say" OnClick="ButtonSay_Click" />
</asp:Panel
I want the enter key to submit as if the "Say" button had been pressed. Yet when focus is in the textbox and I hit enter, nothing happens. All that seems to happen is that the text box loses focus.

Any ideas on how to fix this?

Hi,

I tried your code, the page was successfully submitted when I hit enter.

If it doesn't work for you, you may use the following script to force it.

<asp:TextBox ID="TextBox1" runat="server" Width="90%"onkeypress="if(event.keyCode == 13)document.getElementById('Button1').click();"/>

Hope this helps.


Hi AnthonySteetle,

I have read your question carefully and got a little confused. In your thread, I think you have two questions:

AnthonySteele:


I want the enter key to submit as if the "Say" button had been pressed.

My Sample:

<%@. Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"> protected void ButtonSay_Click(object sender, EventArgs e) { this.Label1.Text = DateTime.Now.ToString(); } protected void TextBoxChat_TextChanged(object sender, EventArgs e) { this.Label1.Text = DateTime.Now.ToString(); }</script><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <asp:Panel ID="PanelChatSay" runat="server" DefaultButton="ButtonSay"> <asp:TextBox ID="TextBoxChat" runat="server" Width="90%" onkeyup="updateDate()" AutoPostBack="false" OnTextChanged="TextBoxChat_TextChanged"/> <asp:Button ID="ButtonSay" runat="server" Text="Say" OnClick="ButtonSay_Click"/> </asp:Panel> </ContentTemplate> </asp:UpdatePanel> <script type="text/javascript" language="javascript"> function updateDate(){ __doPostBack("<%=TextBoxChat.ClientID%>",''); } </script> </form></body></html>

AnthonySteele:


Yet when focus is in the textbox and I hit enter, nothing happens

Please confirm if your submit button is focused when the textbox is clicked. My sample seems it works fine.

Hope this helps. If I misunderstood you, please let me know.


Thank, Raymond. That does the general trick. I have it working as follows:

* remove the defaultButton declaration from the panel.
* Add the following to the page load:

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string enterScript = "if(event.keyCode == 13) document.getElementById('" + ButtonSay.ClientID + "').click();";
TextBoxChat.Attributes.Add("onclick", enterScript);
}
}

Now all I need to do is put input focus back in the text box after postback.

Question: Report Viewer Control (SSRS) inside an Update Panel Control

Hi All,

My web application displays a report on one of its .aspx webpages coded in C#.

I am currently using a ReportViewer control to diplay the server report. I was trying to avoid the refresh of my report on every postback, by including it inside an AJAX Update Panel, it didn't work.

In my next trial, I tried to create a new report viewer control instance programatically and set its properties accordingly and then add this control to the Update panel'sContentTemplateContainer.Controls collection.

It looks like the control gets added to the Update Panel, however, It won't display on the page when it gets renedered. Below is a code snippet.

Please suggest. Thanks.

this.ReportViewer =newReportViewer();

this.ReportViewer.ID ="rvID";

this.ReportViewer.ServerReport.ReportServerUrl =newUri("http://ReportServer");

ReportParameter[] parm =newReportParameter[6];

parm[0] =newReportParameter("a","5");

parm[1] =newReportParameter("b","160");

parm[2] =newReportParameter("c","NYP-BOS");

parm[3] =newReportParameter("d","Coach");

parm[4] =newReportParameter("e","2007-01-01");

parm[5] =newReportParameter("f","2007-05-25");

PanelReport.ContentTemplateContainer.Controls.Add(this.ReportViewer); (adding the Report Viewer to the Panel)

this.ReportViewer.ShowParameterPrompts =false;

this.ReportViewer.ServerReport.SetParameters(parm);

this.ReportViewer.ServerReport.ReportPath ="/Reports/Report1";

Hi!

You should set theAsyncRendering="true"property of the ReportViewer (or setReportViewer.AsyncRendering =True in code-behind) to get async postbacks.

In that way, the report runs in an IFRAME which only refreshes when you re-render the report.

Let me know if it works for you or if you need the reports running in sync with the page. Some time ago I managed to use an UpdatePanel around them, but I ran into some issues that made me come back to the asyncrendering solution.


Hi, Thanks for the response, I have tried using that. It didn't work.

What I have is a Dropdown control, with Autopostback set to true; and an UpdatePanel somewhere else on the page. (the contenttemplate and triggers are empty on the .aspx page)

Programatically, inside the SelectIndexChange evenhandler for the dropdown, I am creating a ReportViewer control and set its properties as needed (also AsynRendering = true).

Now, I add this ReportViewer control to the control collection of the ContentTemplateContainer of the UpdatePanel.

I might be wrong in the sequence of the steps that I am doing...or something else, but whats happening is on the page I can see the report viewer template showing up which has 0 pages.

How and when does the report viewer control or the report gets rendered in the life cycle?

Thanks.


Hi!,

Yes, that may be the problem. The thing is that the SelectedIndexChanged gets fired even after the Page_Load, I'm not exactly sure "when" you have to generate the report, but could be too late. And a ReportViewer in asyncRender won't work inside an UpdatePanel, remeber that is actually an IFRAME.

But, if you are trying to fire an async postback for the SelectedIndexChanged event, the drop down list is the one that should be inside an UpdatePanel (you may already have that).
If that's you case, what you could do is add the ReportViewer outside the update panel and assign its properties in the markup code, and then call theReportViewer.ServerReport.Refresh() method on the SelectedIndexChanged event. If the ReportViewer is set to AsyncRender=true, you should have the same behavior as if it was inside an UpdatePanel.

Hope that helps,


Hi Juan, Based on your response I had partial success.

I made the following changes (Please note that my dropdown list is the first in a set of 3 cascading dropdown lists and all these are not inside any Update panel. They are working as expected whenever the selection changes on the first dropdown.

Took out the ReportViewer control from inside the Update panel and set the properties declaratively (AsyncRendering="true",ProcessingMode="remote",ShowParameterPrompts="false"and also added a <ServerReport> element with correct url and report path


Hi!, Well, I'm glad you are making some progress! :)

Mmmm...I'll start form your second question, and the answer is yes: You have to send the parameters set every time the report is generated.
Another option would be to use the embedded Report Parameters prompts, but it seems that you don't want to do that....
Remember that you can use ServerReport.GetParameters to get all you parameter info.

About the first one, what do you mean exactly when you say "the Report is not refreshing"?? Is trying to refresh, showing the "Generating Report" animated gif and then comes up blank?? It doesn't do anything at all? It comes up with an error??


Hey, that was quick! :)

Yes, I don't want the embedded parameter prompts.

Correct me if I am wrong, ServerReport.GetParameters gives me a readonly collection of parameter info objects right? what could I do with it?

Coming to the first question, By "not refreshing" what I meant was that the webpage sits with the report that it showed me on initial load, even on subsequent SelectIndexChange events (using debugger I can see the event being fired and the parameters being set and the call to report refresh). Its shows me the same report as If nothing happened, (the screen doesn't even flicker) I see the animated gif only on the initial page load.

I think..I would pick "doesn't do anything at all" from the choices that you have listed :)).

Thanks.


Hi!

Well, with the GetParameters you can get the Parameters Name, DataType, DefaultValue, etc,etc.
It's more useful if you want to dynamically create a toolbar or if you want to check that you are entering (SetParameters) all the required parameters with the right names, etc. You can build an array of Parameters and the use it's properties as reference in the SetParameters function.

About the report not refreshing, I would say that it's too late in the page life cycle to do that (as you can see, the SelectedIndexChanged event fires after Page_Load)
Having had a look at my solution, I saw that I'm refreshing the report on Page_Load avoiding to check for Page.IsPostBack.
Just to check, could you try NOT to refresh the report on SelectedIndexChanged and have a Button or something that refreshes the Report AFTER all the appropiate selections have been made in the DropDownLists? Just remember to move the code that sets the parameters and refreshes the reports to Page_Load.

Give it a try, if it works, you'll have the reason for your problem, altought maybe not the solution! :)

Cheers,


Based on the suggestion, I removed the code from the selectindexchange handler and placed something like the below in my page_load to test if the timinig in the lifecycle for the report refresh is the problem. I passed hard coded values to the parameters just so to make sure that the report output generated is different. The initial load was still good but not the postback, nothing happened on postback even from within the page_load. Sorry for all the trouble...I am desperately trying to get this working so as to complete an important assignment by this friday. Thanks.

page_load(object, EventArgs)

{

if (!IsPostback) /* Initial load*/

GenerateReport("a", "b", "c"); (some dummy values for this post)

else

GenerateReport("e", "f", "g"); // on postback

}

void GenerateReport( x,y,z)

{

reportparmeter [] parm = new reportparamete[3];

parm[0] = ..., parm [1] = ...; parm [2] = ...;

reportvwr.ServerReport.Setparameters(parm);

reprtvwr.ServerReprot.Refresh();

}


Mmmm..weird.......how are you generating the second post-back? Are you using a regular post back control like a Button outside an UpdatePanel?


I set the Autopostback on the first dropdownlist to true declaratively. I have a menu on my page too, so I can click on one of the menu items to generate a postback. In this case, should it matter how the postback is fired, because the page_load has hard coded calls for the report generation.

By the by, should the Asynrendering be set to true? (I have it set to true). I can't think of anything else..for now...ok time to go to work.

-Thanks


Hi Juan,

I noticed something, my report refreshes on only normal postbacks and not the asyncpostbacks. Is it okay to assume that, postbacks coming from any controls that are in some way related to an update panel (in or out of it) are always asyncpostbacks?

Thanks.


Hi!

Well, yes, that was the reason of my previous question: The reports will refresh only on a regular postback. If the control that fires the post back is not inside, but set as a trigger for some other update panel, it will fire an async postback.
If you put any control in a page, not inside and not associated with any UpdatePanel, a fire a postback from there, the reports work?

Cheers,


I have a hovermenu extender on my page not part of a update panel. The panel for the hover menu has a couple of link buttons. When I click those link buttons, a normal postback happens and my report gets refreshed.

This is so confusing, I am hoping that there is a thumb rule(s) of some kind for keeping things clear and simple with AJAX (or do's and don'ts). I am new to AJAX and I was wondering if you could recommend me a good design guide which says, how a particular functionality can be accomplished. Right now, I am just developing the code as I discover things, I am afraid if I end up making the code so inflexible for future changes.

Thanks.


What you are experiencing is exactly the same as I was:
The Reports could not be generated as a part of an async postback and in order to make them work properly they should be refreshed not later than in Page_Load...These could be two rules of thumb.

Keep in mind that the ReportViewer runs in a IFRAME while in asyncRendering=true, so it may be worthwhile investigating the interactions between these and AJAX...