Wednesday, March 28, 2012

Page_Load and ajax

I have a simple question. when I use an UpdatePanel control, it is not supposed to refresh the page entirely, only a part of the page.

But why it calls Page_Load event ?

Here's the example used :

<!-- <Snippet2> -->
<%@dotnet.itags.org. 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 Page_Load(object sender, EventArgs e)
{
}
protected void Search_Click(object sender, EventArgs e)
{
SqlDataSource1.SelectParameters["SearchTerm"].DefaultValue =
Server.HtmlEncode(SearchField.Text);
Label1.Text = "Searching for '" +
Server.HtmlEncode(SearchField.Text) + "'";
}

protected void ExampleProductSearch_Click(object sender, EventArgs e)
{
SqlDataSource1.SelectParameters["SearchTerm"].DefaultValue =
Server.HtmlEncode(ExampleProductSearch.Text);
Label1.Text = "Searching for '" +
Server.HtmlEncode(ExampleProductSearch.Text) + "'";
SearchField.Text = ExampleProductSearch.Text;
}
</script
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>UpdatePanel Trigger Example</title>
<style type="text/css">
body {
font-family: Lucida Sans Unicode;
font-size: 10pt;
}
button {
font-family: tahoma;
font-size: 8pt;
}
</style>
</head>
<body>
<form id="form1" runat="server"
defaultbutton="SearchButton" defaultfocus="SearchField">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />

Search for products in the Northwind database. For example,
find products with
<asp:LinkButton ID="ExampleProductSearch" Text="Louisiana" runat="server" OnClick="ExampleProductSearch_Click">
</asp:LinkButton> in the title. <br /><br />
<asp:TextBox ID="SearchField" runat="server"></asp:TextBox>
<asp:Button ID="SearchButton" Text="Submit" OnClick="Search_Click"
runat="server" />

<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional"
runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="SearchButton" />
</Triggers>
<ContentTemplate>

<asp:Label ID="Label1" runat="server"/>
<br />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource1">
<EmptyDataTemplate>
No results to display.
</EmptyDataTemplate>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=.\SQLEXPRESS;AttachDbFilename='H:\Program Files\Microsoft ASP.NET\ASP.NET AJAX Sample Applications\v1.0.61025\Contacts\App_Data\Contacts.mdf';Integrated Security=True;User Instance=True"
SelectCommand="SELECT [Location] FROM
Contacts WHERE ([FirstName] LIKE
'%' + @dotnet.itags.org.SearchTerm + '%')">
<SelectParameters>
<asp:Parameter Name="SearchTerm" Type="String" />
</SelectParameters>
</asp:SqlDataSource>

</ContentTemplate>
</asp:UpdatePanel>

</div>
</form>
</body>
</html>
<!-- </Snippet2> -->

Here's some background info:
http://ajax.asp.net/docs/Overview/intro/partialpagerendering/updatepanelOverview.aspx (see third section on How UpdatePanel's Work)

Basically, during an async postback, the full server page life cycle is executed to the point of rendering similar to a "regular" postback. At the render phase for an async postback the framework determines that only the content of UpdatePanels need to be refreshed.

If you want to not run code during an async postback, use the ScriptManager.IsInAsyncPostBack to check if you are in async postback and then take action.

http://ajax.asp.net/docs/mref/db2bbeac-e762-e1ac-ca74-1a3e6ab76979.aspx

Page_Load always executed - can this be changed?

Hello,

I started using <asp:UpdatePanel> to update controls content in my page.

This work really great, and the Look and Feel are perfect.

However, in the page I load many controls dynamically in the Page_Load - it can reach thousands of controls.

Each of the controls contains UpdatePanel that has UpdateMode of "Conditional" - this let me change the contents of each control without affecting the other controls.But, and here finally come the catch, I noticed the whole Page_Load is executed. When there will be thousands of controls, I would like to Load them only once, then have AJAX code that would not cause the whole Page_Load to run again.

Is this possible? Can we make the AJAX read other page maybe?

Thanks in advance. :)

If you want to only run the code on the initial Page Load, you can throw everything in if(!Page.IsPostBack && !Page.IsCallBack). We use that method for most stuff, but if you use 3rd party controls, there may be some issues... We use telerik controls and they do a post back like event, which isn't caught by that.

Well, if I add if (!Page.IsPostBack) then the controls are lost, as they're not static in the page but rather created on the fly using Page.LoadControl method.

What I'm trying to achieve is that different page will be called by the AJAX "engine". So far my investigations on this bore no fruit. Any ideas?

Page_Validators in AJAX.NET problem.

Good day,

Using ASP.NET 2.0 AJAX Extensions 1.0 (1.0.61025) I am getting different output from my dev environment and another Windows 2003 server. It is causing a null reference exception because of the absence of some script, as follows.

A page that demonstrates the problem. Essentially a Textbox with a Validator in an UpdatePanel. The Textbox is hidden in a partial page update and the validator isn't removed from Page_Validators, leading to a null reference exception. Here it is.

1<%@dotnet.itags.org. Page Language="C#" %>
2<html xmlns="http://www.w3.org/1999/xhtml">
3<head>
4<title>AJAX Test</title>
5<script runat="server">
6 protected void Button1_Click(object sender, EventArgs e)
7 {
8 TextBox1.Visible = false;
9 }
10</script>
11</head>
12<body>
13 <form id="form1" runat="server">
14 <div>
15
16 <asp:ScriptManager ID="ScriptManager1" runat="server" />
17 <asp:UpdatePanel ID="UpdatePanel1" runat="server"><ContentTemplate>
18 <asp:TextBox ID="TextBox1" runat="server" />
19 <asp:RequiredFieldValidator ID="req" runat="server" ControlToValidate="TextBox1">Bad!</asp:RequiredFieldValidator>
20 <br />
21 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" />
22 </ContentTemplate></asp:UpdatePanel>
23
24 </div>
25 </form>
26</body>
27</html>
Here is the output from the dev environment that works:
1<html xmlns="http://www.w3.org/1999/xhtml">
2<head>
3<title>AJAX Test</title>
45</head>
6<body>
7 <form name="form1" method="post" action="ajaxTest.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="form1">
8<div>
9<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
10<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
11<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTEzMDMxMDUwMDhkZDuvWiPpfDn3oBIdbrlUSDkq1FdR" />
12</div>
1314<script type="text/javascript">
15<!--
16var theForm = document.forms['form1'];
17if (!theForm) {
18 theForm = document.form1;
19}
20function __doPostBack(eventTarget, eventArgument) {
21 if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
22 theForm.__EVENTTARGET.value = eventTarget;
23 theForm.__EVENTARGUMENT.value = eventArgument;
24 theForm.submit();
25 }
26}
27// -->2829</script>
303132<script src="/WebResource.axd?d=aw9IrFUp2_oQ8Owgb8KfHw2&t=633198061661875000" type="text/javascript"></script>
333435<script src="/ScriptResource.axd?d=CKqJO5pnLiMiiKIAPSjUhlVSq_XssPmgCzQ3imV6c-ZI8ou-jtF3g7zNM6zAzFuwj0cj4E-Yc9RTfjMvluxK4g2&t=633198061661875000" type="text/javascript"></script>
36<script src="/ScriptResource.axd?d=cKz-vvqLo1ehaWyVHnXCamccZCS0TLr_WkNiTAu40bnCXSUBzVyHwrKIRYpIqnRFj0bnuLFtFlIG1uLE2IU0HlTdJFkwvyWnrxefUsmR0881&t=633278094321250000" type="text/javascript"></script>
37<script src="/ScriptResource.axd?d=cKz-vvqLo1ehaWyVHnXCamccZCS0TLr_WkNiTAu40bnCXSUBzVyHwrKIRYpIqnRFj0bnuLFtFlIG1uLE2IU0HjrmGHRUhUO2-euEh4H2gbI1&t=633278094321250000" type="text/javascript"></script>
38<script type="text/javascript">
39<!--
40function WebForm_OnSubmit() {
41if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false;
42return true;
43}
44// -->45</script>
4647 <div>
4849 <script type="text/javascript">
50//<![CDATA[51Sys.WebForms.PageRequestManager._initialize('ScriptManager1', document.getElementById('form1'));
52Sys.WebForms.PageRequestManager.getInstance()._updateControls(['tUpdatePanel1'], [], [], 90);
53//]]>
54</script>
5556 <div id="UpdatePanel1">
57
58 <input name="TextBox1" type="text" id="TextBox1" />
59 <span id="req" style="color:Red;visibility:hidden;">Bad!</span>
60 <br />
61 <input type="submit" name="Button1" value="" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("Button1", "", true, "", "", false, false))" id="Button1" />
62
6364</div>
6566 </div>
67
68<script type="text/javascript">
69<!--
70var Page_Validators = new Array(document.getElementById("req"));
71// -->72</script>
7374<script type="text/javascript">
75<!--
76var req = document.all ? document.all["req"] : document.getElementById("req");
77req.controltovalidate = "TextBox1";
78req.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
79req.initialvalue = "";
80// -->81</script>
8283<div>
8485<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwKV1JT3DQLs0bLrBgKM54rGBh9lq902q1zs4nZQoQSzXWrrFvC2" />
86</div>
8788<script type="text/javascript">
89<!--
90var Page_ValidationActive = false;
91if (typeof(ValidatorOnLoad) == "function") {
92 ValidatorOnLoad();
93}
9495function ValidatorOnSubmit() {
96 if (Page_ValidationActive) {
97 return ValidatorCommonOnSubmit();
98 }
99 else {
100 return true;
101 }
102}
103// -->104</script>
105
106<script type="text/javascript">
107<!--
108Sys.Application.initialize();
109110document.getElementById('req').dispose = function() {
111 Array.remove(Page_Validators, document.getElementById('req'));
112}
113// -->114</script>
115</form>
116</body>
117</html>
118

Here is output from a different server that fails.

1<html xmlns="http://www.w3.org/1999/xhtml">2<head>3<title>AJAX Test</title>45</head>6<body>7 <form name="form1" method="post" action="ajaxTest.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="form1">8<div>9<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />10<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />11<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTEzMDMxMDUwMDhkZBFseLlnE6oRW+2WytSmHIxuhR3k" />12</div>1314<script type="text/javascript">15<!--16var theForm = document.forms['form1'];17if (!theForm) {18 theForm = document.form1;19}20function __doPostBack(eventTarget, eventArgument) {21 if (!theForm.onsubmit || (theForm.onsubmit() != false)) {22 theForm.__EVENTTARGET.value = eventTarget;23 theForm.__EVENTARGUMENT.value = eventArgument;24 theForm.submit();25 }26}27// -->2829</script>303132<script src="/WebResource.axd?d=y79a8WX0nIrEh3fkGSsX9A2&t=633281399937474336" type="text/javascript"></script>333435<script src="/WebResource.axd?d=w26mxAmgRXp-rT77oPfALL7gzYUT-X6oWLHzd_D6LjY1&t=633281399937474336" type="text/javascript"></script>36<script src="/ScriptResource.axd?d=wZTJCSpVLa8cXWFJgmiuXX-hnAsgClz1-CgGif5xa_-p3CzrOtmsIfh3Y28aQcYFVC5wnr2IJhBHoh2c9Zc0Ch0RynufR4TLZTewW0cBhsc1&t=633281590101841744" type="text/javascript"></script>37<script src="/ScriptResource.axd?d=wZTJCSpVLa8cXWFJgmiuXX-hnAsgClz1-CgGif5xa_-p3CzrOtmsIfh3Y28aQcYFVC5wnr2IJhBHoh2c9Zc0CrgGo9Nt84M88yWLG3iczXI1&t=633281590101841744" type="text/javascript"></script>38<script type="text/javascript">39<!--40function WebForm_OnSubmit() {41if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false;42return true;43}44// -->45</script>4647 <div>4849 <script type="text/javascript">50//<![CDATA[51Sys.WebForms.PageRequestManager._initialize('ScriptManager1', document.getElementById('form1'));52Sys.WebForms.PageRequestManager.getInstance()._updateControls(['tUpdatePanel1'], [], [], 90);53//]]>54</script>5556 <div id="UpdatePanel1">5758 <input name="TextBox1" type="text" id="TextBox1" />59 <span id="req" style="color:Red;visibility:hidden;">Bad!</span>60 <br />61 <input type="submit" name="Button1" value="" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("Button1", "", true, "", "", false, false))" id="Button1" />626364</div>6566 </div>6768<script type="text/javascript">69<!--70var Page_Validators = new Array(document.getElementById("req"));71// -->72</script>7374<script type="text/javascript">75<!--76var req = document.all ? document.all["req"] : document.getElementById("req");77req.controltovalidate = "TextBox1";78req.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";79req.initialvalue = "";80// -->81</script>8283<div>8485<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwKvmrnGBwLs0bLrBgKM54rGBh5nv4YQrwGF0j7OWce2dFyfGsmj" />86</div>8788<script type="text/javascript">89<!--90var Page_ValidationActive = false;91if (typeof(ValidatorOnLoad) == "function") {92 ValidatorOnLoad();93}9495function ValidatorOnSubmit() {96 if (Page_ValidationActive) {97 return ValidatorCommonOnSubmit();98 }99 else {100 return true;101 }102}103// -->104</script>105106<script type="text/javascript">107<!--108Sys.Application.initialize();109// -->110</script>111</form>112</body>113</html>114
The working machine is a dev machine with a long history of messing around.The failing machine is a freshly installed Windows 2003 install with only critical updates, .Net Framework 2.0, Ajax Extensions.I uninstalled and reinstalled Ajax Extensions on the dev machine using the same msi.
I am unable to figure out what is different in the configuration.

Any suggestions would be tremendous!

Thanks,

Craig


Validation controls, which includes theBaseCompareValidator,BaseValidator,CompareValidator,CustomValidator,RangeValidator,RegularExpressionValidator,RequiredFieldValidator, andValidationSummary control are not compatible with UpdatePanel

See it here

http://weblogs.asp.net/scottgu/archive/2007/01/25/links-to-asp-net-ajax-1-0-resources-and-answers-to-some-common-questions.aspx

You can downlaod compatible ersion of validators from here

http://blogs.msdn.com/mattgi/archive/2007/01/23/asp-net-ajax-validators.aspx


Thanks muchly! :)

Page_Validator undefined Error??

Hi,

I have a jscript function calledEnableAll(). The following is the Function:-

function EnableAll()

{

alert("Hai");

EnableAllValidators(false);

EnableValidator('valreq_Salutation',true);

ShowError();

}

This i called on a button click. but only the alert message is pop_up. after that im getting this errorPage_Validators is undefined Jscript runtime error .

What was the solution for this??

How can i over come this...

Hi,

I'm not quite sure why you use this function. It seems you want to enable all validators on the page according to the name of the function.

The error is caused by an javascript exception, looks like it uses an object that doesn't exist internally. And I can't tell since I don't know your implementation in EnableAllValidators and EnableValidator function. You'd better use Visual Studio to debug your javascript to find out the reason and resolve it.

Paged GridView in update panel doesnt work

Hi, I have paged grid view inside an update panel but when I try to change the page in the grid view nothing happens, any ideas why? thanks for your help.

Could you post your code so we can see exactly what you are doing?


Yes, here is the gridviewcode

<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="1" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="12" AutoGenerateColumns="False">
<FooterStyle BackColor="White" ForeColor="#000066" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="# Cuota" HeaderText="# Cuota" />
<asp:BoundField DataField="Saldo Inicial" HeaderText="Saldo Inicial" />
<asp:BoundField DataField="MontoInteres" HeaderText="Monto Interes" DataFormatString="{0:C}" HtmlEncode="False" />
<asp:BoundField DataField="Monto Cuota" HeaderText="Monto Cuota" />
<asp:BoundField DataField="MontoCapital" HeaderText="Monto Capital" DataFormatString="{0:C}" HtmlEncode="False" />
</Columns>
</asp:GridView>

The grid view gets filled with data, it just wont let me browse through the grid view pages and it works outside the update panel.


Nevermind, outside the update panel it just postbacks but I hadnt notice the information is the same. I dont have any eventhandler set on the gridview.


I made it work. I just added this code


protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{

GridView1.DataSource = ViewState["DataTable"] as DataTable ;
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}

Thanks for your help.

PageError event of scriptmanager not firing

I have a content page that has a master page. I have an updatepanel and a scriptmanger in my content page. I defined a handler for OnPageError for the scriptmanager and defined a error template for the scriptmanager but when I set the e.errormessage in the OnPageError event, but if I set a break point in the event, the break point is never reached and the error message in the template still displays 'unknown error' Any ideas?

if I put a button on the page and in the click event of the button i manually throw and error.

thrownewException("error button clicked");

the event fires and works fine.

but if I put some invalid characters like '<img src' inside a textbox and then click the button (removing the throw) then the OnPageError isn't fired

PageError doesnt preserve stack trace

Hi,

I use the ScriptManager.PageError event in order to catch internal exceptions and rethrow them to be handled by the Application_Error event, just like in any non-ATLAS page.

The problem is that ATLAS clears the exception's stack trace and restarts it only from the PageError event handler itself.

I'm having hard time resolving the problems without having the original stack trace.

Any ideas?

Thanks,

Lior

hello.

are you sure about this? i seem to recall cehcking for a stack of an exception during the error handling...i maybe wrong since i don't have atlas installed here and can't check it right now...


Yes, I created an exception inside a function of a UserControl I'm using in my page, and this is the stack trace of the e.Error exception returned by theScriptManager_PageError event.

As you can see, there is no stack trace before the PageError event. When not using ATLAS, the Server.GetLastError() function returns the original exception with the original stack trace as an InnerException.

at ***.Web.UI.***.TheScriptManager_PageError(Object sender, PageErrorEventArgs e) in ****.aspx.cs:line 179

at Microsoft.Web.UI.ScriptManager.OnPageError(PageErrorEventArgs e)

at Microsoft.Web.UI.ScriptManager.OnPageError(Exception ex)

at Microsoft.Web.UI.ScriptManager.OnPageError(Object sender, EventArgs e)

at System.Web.UI.TemplateControl.OnError(EventArgs e)

at System.Web.UI.Page.HandleError(Exception e)

at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

Lior


hello.

hum...here's an excerpt of a stack trace from an aspx on the error event of the scriptmanager:

at ASP.error.h(Object sender, EventArgs args) in d:\atlas\AtlasWebSite2\error.ascx:line 7
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

as you can see, the error comes from an usercontrol which is inside an updatepanel,...


Hi,

My mistake. I did a "throw e.Error" in the PageError handler which, of curse, cleared the stack trace...

Thanks for your help,

Lior


I have the same problem in my page, but your post don't solve my problem. I did the same thing you did and rethrow the exception e.Error in the Script Manager PageError event hadler but the exception is again catched by the atlas framwork not by the application error handler and a popup window shows with the exception. Why is this happening?

hello.

well, if i recall correctly, scriptmanager catches all page erros and removes them so that the current request can be handled correctly. if it didn't do this, the client side would never receive the correct response (ie, the response wouldn't be in the correct format). if you need to log the error on the server, then handle the scriptmanager pageerror event and perform the loggin there. instead of showing the popup with the error, you can build your own error template which will be shown to the user in those cases...


No this is not what I need. The problem is this: when an exception is thrown i my atlas page inside an update panel a javascript win pops up with an message "Unhadled exception". I don't want that! I want that exception to be catch from a httpHandler that uses the Server.GetLastError() method and shows a message in the ErrorPage.aspx. This is it. How can I do that?

I tried to do this like it is said in previous posts

ScriptManager1.PageError += new Microsoft.Web.UI.PageErrorEventHandler(sm_PageError);

protected void sm_PageError(object sender, Microsoft.Web.UI.PageErrorEventArgs e) {
throw e.Error;
}

but it doesn't work.


I'm sorry the mistake was in my code. :)