Wednesday, March 28, 2012

Page with AJAX controls posts back twice to the server

I have a form containing three AJAX UpdatePanels, two of which contain a pair of listboxes and a pair of buttons, with the third one containing a pair of radio buttons in a radiobutton list and either three CascadingDropDown lists or two CascadingDropDown lists and a textbox depending on which radio button is selected. The only other control on my form is a button to submit the information on the form to the server.

One thing I've noticed is the information gets posted back to the server twice when the button is clicked. This causes a duplicate record to be written to two tables and a SQL exception being thrown when it tries to write a duplicate record to a third table since it violates that table's primary key constraint. At first, I thought the cause might've been due to the submit button being contained in the third UpdatePanel I mentioned, so I removed it from there and placed it by itself ... but the problem still occurs. One other thing I've noticed is that when data for one of the UpdatePanels is to be updated via a postback to the server, the other two UpdatePanels act as if they're also being posted back to the server; in other words, all three panels noticeably flicker simultaneously. I have a sneaking suspicion this may somehow tie into my entire page being posted back twice when the submit button is clicked, but I'm not at all sure.

What can I do to prevent my page from being posted back twice?

Hi,

any sync postback at the server side is almost identical to regual postback including:

- all control values are posted to the server
- Viewstate is transferred to the server and back

The most important difference is in the rendering phass: only update panels are rendered and their content transferred to the client

So, you must design your application in such a way, that removing all update panels will not break server logic. UpdatePanels reduce flickering, but they don't change how server code process data.

-yuriy


I think there a couple things that can cause this... I think ImageButtons can get rendered as "Submit" buttons, and have a __doPostBack call attached to their OnClick, which seems to make a double postback. Also, I think a button has a UseSubmitBehavior property... try setting that to false.

Page with update panel doesnt show correct information when I back into the page

I have this page that I'd like to use update panels on. There are three controls on the page. I'd like to have the first dropdown control fire a second dropdown and then that one fire a gridview. I'd like the 2nd dropdown and the gridview to be in update panels. So when a user makes a general category selection in the first dropdown, the 2nd one will list the more specific categories (those related to the first dropdown selection) and then when the user picks a more specific category the gridview is filled with with data specific to that 2nd more specific category. I've got this all working fine. The the user clicks the "details" link in the gridview and they see full details about their selection from the gridview. But then when they click the "back" button in their browser, it takes them back to the page with the 2 dropdowns and the gridview but it's not in the state they left it. Ideally, they should see the same thing they saw before they clicked the "details" link.... their first selection int he first dropdown, their more specific category in the 2nd dropdown and the gridview filled with info relating to that 2nd dropdown. But that's not what I get. What am I missing?

hello.

well, you're not missing anything. it's simply the way ajax pages work. i think that you should take a look at the history control available on the future bits

http://msmvps.com/blogs/luisabreu/archive/2007/05/07/may-future-bits-the-history-control.aspx

Page.ClientScript.RegisterStartupScript in updatepanel problem with Beta1.0 ??

Open a new window fails!!! (but with CTP OK!)

protected override void OnClick(EventArgs e)
{
if (grid != null && grid.DataKeyNames.Length > 0)
{
int[] selected = grid.GetSelectedIndexes();
if (selected.Length > 0)
{
grid.SelectedIndex = selected[0];
DataKey dataKey = grid.SelectedDataKey;
if (dataKey != null)
{
string separator1;
if (DialogNavigateUrl.ToString().IndexOf("?") != -1)
{
separator1 = "&";
}
else
{
separator1 = "?";
}
StringBuilder sb = new StringBuilder();
string separator2 = string.Empty;
IDictionaryEnumerator enumerator = dataKey.Values.GetEnumerator();
while (enumerator.MoveNext())
{
sb.Append(separator2);
sb.Append(enumerator.Key);
sb.Append("=");
sb.Append(enumerator.Value);
separator2 = "&";
}
string format;
format = "window.open('{0}{5}{6}{7}Parent={4}',null,'height={1},width={2},status=1,toolbar=0,menubar=0,location={3},resizable=1,scrollbars=1');";
string script =
String.Format(CultureInfo.CurrentCulture, format, DialogNavigateUrl.ToString().Replace("~/", ""), DialogHeight.Value, DialogWidth.Value,
Convert.ToByte(DialogLocation), this.ClientID, separator1, sb.ToString(), separator2);
Type type = this.GetType();
if (!Page.ClientScript.IsStartupScriptRegistered("clientScript"))
{
Page.ClientScript.RegisterStartupScript(type, "clientScript", script, true);
}
}
}
}
base.OnClick(e);
}

For the control to work inside an UpdatePanel you need to call the new static registration APIs on the ScriptManager class. They have basically the same parameters as the Page.ClientScript methods but the new first parameter is the control doing the registration (usually "this").

Thanks,

Eilon


More info about script registration in my recent post:http://forums.asp.net/thread/1440058.aspx

Thanks,

Eilon

Page.ClientScript.RegisterStartupScript in Ajax beta 2

----Code in Module (app_code) folder

Public Sub ShowMessage(ByVal msg As String, ByVal ObjPage As Page)

Try
Dim RegKeyname As String = "infmsg"
If ObjPage.ClientScript.IsStartupScriptRegistered(RegKeyname) Then

RegKeyname = RegKeyname & Now.GetHashCode.ToString("x")
Else
RegKeyname = "infmsg"
End If

ObjPage.ClientScript.RegisterStartupScript(ObjPage.GetType, RegKeyname, String.Format("alert('{0}');", msg), True)


Catch ex As Exception

End Try

End Sub

----------

I used to call this function from any of my asp.net Pages to display an alert message this worked till atlas july ctp now it doenst seem to work in ajax beta 2.

Note : This worked in Normal Pages as well as Pages having an Update panel

Any one any clue ... how to get it back to work

Hi Asifsolkar

I think you should use ScriptManger'sRegisterStartupScript method. There was change between CTP and BETA versions of ASP.NET AJAX ext.

(seehttp://ajax.asp.net/docs/mref/8b90a607-02c9-3c22-6cec-4628c98ccd25.aspx )

Have a nice day

Milo

Page.IsCallback equivalent

What is the Atlas equivalent to the value returned by Page.IsCallback?

As I understand it, since the call is just an intercepted postback, Page.IsPostBack will be True on an Atlas callback. I don't think there is a way to tell if you're dealing with a "True" PostBack or a callback, but I also don't think the event could be called more than one way, so if you need to check later on in your code how you got to where you are, set a member variable in the event handler.


ScriptManager.GetCurrent(Page).IsInPartialRenderingMode

Thanks folks. I had noticedIsInPartialRenderingMode and found it seems to do the job. I do need a definitive answer as it affects how I create my products. Can anyone of the Atlas team chime in?


hello.

as you can see, i'm not in the atlas team. however, i'd like to confirm Rama's answer. btw, currently, a partial postaback is identified by a header called delta which has its value set to true during a partial postback. during the init event, the scriptmanager control looks for that header, and when it has the value true, it initializes the _inPartialRenderingMode field which is used to "feed" the result of the IsInPartialRenderingMode property.

Page.Redirect From Control Event Using Atlas

I am a newbie in atlas..just a couple of hour of experience.

I've managed to create a simple project with sucess, and all works well. But, in a certain event of an treeview control, the "SelectedNodeChanged", i need to redirect the page to another URL. The Page.Redirect runs it the server, but the page doesn't do the postback. How can i force the postback, in a certain event?

Thank you very much.

Well...i found out that the Page.Redirect in Atlas doesn't work very well.

I've got this solution, it's not the best way to do this, but it works,

Page.ClientScript.RegisterStartupScript(this.GetType(),"redirect",@."window.location.href='default.aspx';",true)

Page.RegisterClientScriptBlock breaks Ajax?

Hi -

I am using

Page.RegisterClientScriptBlock to write a script dynamically to my webpage. For some reason, this seems to break some of my other java script (don't get called at all).

I'd be grateful for any idea experience with this!!! Thanks!!!!

Oliver

You want to use the ScriptManager version of that same method instead, the Page's version doesn't work withthe ajax framework.


Paul -

thanks so much. This was quite useful. May I ask you a follow-up question? While Ajax now works on the page, one additional control that loads its Javascript from a file still doesn't ... is there anything special I need to consider?

Thanks again,

Oliver


Well, if that control doesn't load the file through the scriptmanager, that'll be a problem for you as well. What's the control? Also, any .js files need to have a line at the end of them:

if(Sys && Sys.Application)
Sys.Application.notifyScriptLoaded();

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. :)

PageFlakes.com Initial Load

Does anyone know how PageFlakes.com does the initial "Loading..." progress when you first go towww.pageflakes.com? I would like to be able to set a page to show a "Loading..." progress panel when users first go to the page.

I second that request - it may be flash, but it certainly is cool.

Also cool is the little dashes when you move a control around (denoting the size).

I also really wish the Atlas Tools team would come up with an RSS reader that was as robust as PageFlakes.


Well as far as I understood Pageflakes.com was done in Atlas that's why I was asking how they did the initial "loading" because I was hoping someone may be able to explain how to do something like that with Atlas.
I'm pretty sure they're using an UpdateProgress control with an animated GIF file. I'm also pretty sure that the GIF is included in the Atlas sample applications.
But how do you use an UpdateProgress control with the initial load of a page and not a PostBack--also, how did they make it so the UpdateProgress control replaces all of the UpdatePanels while loading?

Look at my thread here:

http://forums.asp.net/thread/1256936.aspx

pageLoad and pageUnload called when using PageMethods ?

I have pageLoad and pageUnload functions in my page where I do my initialization and cleanup. I also use UpdatePanels and PageMethods. I am noticing that pageLoad and pageUnload methods are getting called on every PageMethod (ajax) call !!.

Doesn't pageLoad and pageUnload correspond to window.load and window.unload events respectively ?

Basically, I want methods which should be called when _entire_ page is loaded or unloaded and should not be called while using PageMethods or postbacks from within UpdatePanel

Please guide.

Regards & thanks

Kapil


Hi ksachdeva17,

I hope i understand your situation correctly. You don't want that the page life cycle will be invoked when there is an event triggered by an action from a control inside your updatepanel (or trigger). Well the situation on the server will be the same when you're using an updatepanel. The async postback will take the same cycle as an synchronous postback. The thing that is different is the rendering of the page. The controls in your updatepanel will only be rendered and not the whole page. I hope this will make things clear for you.

Regards,


Thanks Dennis,

You are saying that window.onload and window.unload (DOM) events will occur if we make XMLHttprequest from the page, I would guess they should not as XMLHttpRequest is independent of browser post !!. I understand that on server side async postback would take the same cycle as synchronous postback but on the page (in client browser) it should not.

Regards

Kapil


Hi Kapil,

I was saying that the page life cycle on the server will stay the same no matter if it's a synchronous of asynchronous postback. I found this in the documentation of Ajax.

Client Page Life-cycle Events

During ordinary page processing in the browser, thewindow.onload DOM event is raised when the page first loads. Similarly, thewindow.onunload DOM event is raised when the page is refreshed or when the user moves away from the page.

However, these events are not raised during asynchronous postbacks. To help you manage these types of events for asynchronous postbacks, the PageRequestManager class exposes a set of events. These resemblewindow.load and other DOM events, but they also occur during asynchronous postbacks. For each asynchronous postback, all page events in the PageRequestManager class are raised and any attached event handlers are called.

Hope this helps!

Regards,


Thanks Dennis,

So my inference is that pageLoad is not same as window.onload. If you could please verify my understanding. I think I should be able to add the event handler using $addHandler with 'load' as an event name to execute things when page is loaded for the first time (no async) . Correct ?

Regards

Kapil


HI Kapil,

PageLoad and window.load are not the same indeed. you can handle also the logic you want in you code behind using thefollowing funciton:

if

(!ScriptManager.GetCurrent(this).IsInAsyncPostBack)

{

myTextBox.Text =

"Test";

}

Probably you already see what it's doing. It will check if it's in a asynchronous postback, when you want to handle some functionality when the page is in a synchronous postback you can you the statement above.

It is also possible to add a handeler to the load event of your window! like you suggested

Good luck

Regards,

pageLoad javascript function not being called

for some reason the javascript pageLoad method is not being called

the javascript is in scirbble.js

the example i have followed informs me that the pageLoad method should be ran when the atlas script manager control has loaded.

Is this corret.

Could someone please point me in the right direction for getting the below code to work

Below is the javascript and aspx code

function pageLoad()
{
var surface = document.getElementById("drawingSurface");
image = surface.getElementsByTagName("IMG")[0];
originalSrc = image.src;

surface.attachEvent("onmousedown", startStroke);
surface.attachEvent("onmouseup", endStroke);
surface.attachEvent("onmouseout", endStroke);
surface.attachEvent("onmousemove", addPoints);
}

form id="form1" runat="server">
<Atlas:ScriptManager ID="AtlasScriptManager" runat="server" >
<Services>
<Atlas:ServiceReference Path="ScribbleService.asmx" />
</Services>
<Scripts>
<Atlas:ScriptReference Path="ScriptLibrary\Scribble.js" />
</Scripts>
</Atlas:ScriptManager>
<div id="drawingSurface"
style="border:solid 1px black;height:200px;width:200px">
<img alt="Scribble" src="http://pics.10026.com/?src=ScribbleImage.ashx"
style="height:200px;width:200px" />
</div>
</form>

i have the same problem since the last release. I had pageLoad() methods which were able to set elements on the initial loading which no longer fire automatically :?(

As a workaround, you can attach to thePageRequestManager events like so :

<script type="text/javascript"> Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoad);</script>

when i do the above mentioned work around i get an error

'Sys.WebForms.PageRequestManager' is null or not an object

i have tried adding the script above and below the sript manager html elements but it makes no diffrence.

below is the aspx page

any help would glady be appreciated.

<headrunat="server">

<title>Atlas Scribble Sample</title>

</

head><body><formid="form1"runat="server"><Atlas:ScriptManagerID="AtlasScriptManager"runat="server"EnablePartialRendering=true><Services><Atlas:ServiceReferencePath="ScribbleService.asmx"/></Services><Scripts><Atlas:ScriptReferencePath="ScriptLibrary\Scribble.js"/></Scripts></Atlas:ScriptManager><divid="drawingSurface"style="border:solid 1px black;height:200px;width:200px"><imgalt="Scribble"src="ScribbleImage.ashx"style="height:200px;width:200px"/></div><scripttype="text/javascript">

Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoad);

</script></form>

</

body>

</

html>
throw an alert into your pageLoad() function to see if it's getting called; my guess is that it is, at least nothing you've posted here would prevent it. The issue I see is that the element 'surface' isn't going to respond to the attachEvent function as you have it written, at least not in this framework. You could try to us $addHandler(surface,'onmousedown',startStroke); instead.

pageLoad fires before script references are loaded

I have an aspx page with:

- a scriptmanager that has 2 script references. Both scripts have the "if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();" line at their end.

- a script section with a pageLoad function that calls a function defined in one of the 2 script references.

- an iframe (with src set to about:blank).

Result:

I get an "object undefined" error in the pageLoad function. with fiddler and in the debugger I can see that my script rerefences have not yet been loaded. As fas as I know, they should! It always worked until we added the iframe control. Removing the iframe control resolves the problem. To me this looks like an error in ajax where the pageLoad is executed on the load of the iframe contents instead of on the load of the main page.

Anyone any suggestion?

Could you share some code that reproduces this bug? I was unable to get the behavior you describe.

Are you using a function named pageLoad? Or Sys.Application.add_load(...)? Or Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(...)? Code would help a lot.


Thanks for looking into the problem. I will try to assemble a minimal solution that exposes the bug. BTW: it is a pageLoad function. In the debugger I saw that Ajax in the onload event looks if it exists and, if so, calls it. That's also how I found out that it gets called twice from this event handler. Give me some time to assemble the solution.

Thanks agian,

Erwin

PageMethod called within User Control (ascx)

Hi all,

I am trying to call a PageMethod on an AutoComplete extender within an ascx (user control). I am able to do so when the extender sits directly on an ASPX (web form) but would like to reuse the component.

I know to decorate the method with [WebMethod] and [ScriptMethod] attributes and also to make the method static. I know, too, that the parameter names must match the expected signature.

Is it possible to place Page Methods within User Controls or do they have to sit on ASPX pages?

Thanks in advance,

MIKE

I have seen a couple of blog posts saying no and I was trying to do something similar last night and couldn't make it work. I would really perfer the AutoComplete extender and the NumericUpDown extender to have the option to fire events or at least non static methods but I don't think that will be possible under the current Ajax setup.

pagemethod call code sample

Can anyont point me to a code sample where a call is made to a server page method from the client script code?

thanks!

Pratibha

Hi,

please checkthis post from my blog.

pageLoaded event

I have created an ASP.NET custom server control that is updated using AJAX via an UpdatePanel using the Tick event of a Timer control as the asyc trigger. I need to execute javascript each time a partial postback returns so I am using the pageLoaded event. This works perfectly in IE7 but doesn't fire in Firefox 2.0.0.3 or Opera 9. On other browsers it never fires the pageLoaded event, but it does the AJAX updating and other javascript works. I am registering the client code during my control's render method.. I have also tried using the endRequest event. Please help. Why won't it work on other browsers.

Below is the rendered HTML:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head><title>Untitled Page</title><meta content="text/html;charset=iso-8859-1" http-equiv="content-type" /><meta content="NO-CACHE" http-equiv="PRAGMA" /><meta content="NO-CACHE" http-equiv="CACHE-CONTROL" /><meta content="0" http-equiv="EXPIRES" /><style type='text/css'> a.info:active{z-index:0; position:relative; background-color:#FFF647} a.info label{display: none} a.info:active label{ display:inline; position:absolute; white-space:normal; text-wrap:normal; word-wrap:break-word; left:label.parent.width; top:label.parent.height; width:250px; border:1px solid #91907C; background-color:#EAE7C6; z-index:-1; } </style> </head><body> <form name="form1" method="post" action="Default.aspx" id="form1"><div><input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" /><input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" /><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTEwMzQxMTA4OTkPZBYCAgMPZBYCAgEPZBYCAgIPZBYCZg9kFgJmDxYGHgtjZWxscGFkZGluZwUBMB4LY2VsbHNwYWNpbmcFATAeBXN0eWxlBSlwYWRkaW5nOjVweDt6LWluZGV4OjIwO3Bvc2l0aW9uOmFic29sdXRlO2RkMUSTfpjSwghJETl9/Jgkha9oZaA=" /></div><script type="text/javascript"><!--var theForm = document.forms['form1'];if (!theForm) { theForm = document.form1;}function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); }}// --></script><script src="/WebResource.axd?d=9DvoInn8tlftzCiBPvQagg2&t=632974035101093750" type="text/javascript"></script><script src="/ScriptResource.axd?d=WAnysv6JNp-Tgl_8AndGJnGXdfOUUPdccvGwkhkSJu2uP8RLi_go1jCrdTe0jCpJF0u8GYhfCflHcjQdOJTaXMeB6qn3C9aitPrPuScmgSM1&t=633063657262888841" type="text/javascript"></script><script src="/ScriptResource.axd?d=WAnysv6JNp-Tgl_8AndGJnGXdfOUUPdccvGwkhkSJu2uP8RLi_go1jCrdTe0jCpJF0u8GYhfCflHcjQdOJTaXOmCYkHGf_k8diSD9UcMEoc1&t=633063657262888841" type="text/javascript"></script><script src="/ScriptResource.axd?d=WAnysv6JNp-Tgl_8AndGJnGXdfOUUPdccvGwkhkSJu2uP8RLi_go1jCrdTe0jCpJF0u8GYhfCflHcjQdOJTaXLsHgXZk2LxHv8oSN-rIGKs1&t=633063657262888841" type="text/javascript"></script> <span id="events" style="font-size:Small;"><span id="events_timer1" style="visibility:hidden;display:none;"></span><input name="events$ctl00" type="hidden" id="events_ctl00" /><div id="events_UpdatePanel1"><table cellpadding="0" cellspacing="0" style="padding:5px;z-index:20;position:absolute;"><tr><td rowspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-bottom:5px;padding-top:5px;"><img src="../images/greenshd.gif" alt="The IT Road Show.........................." /></td><td style="padding-left:5px;">Tuesday 24 Apr</td><td style="padding-left:15px;">3:30 pm</td></tr><tr><td colspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-left:5px;padding-bottom:5px;"><a href="http://www.nova100.com.au" id="events_3160" EventsEventDatesId="3160" LabelId="events_label_0_3160" onfocus="document.getElementById('events_ctl00').value = this.LabelId" onblur="document.getElementById('events_ctl00').value = ''" class="info">The IT Road Show.......................... </a></td></tr><tr><td rowspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-bottom:5px;padding-top:5px;"><img src="../images/AKMAL_OVER.gif" alt="The Akmal Show" /></td><td style="padding-left:5px;">Tuesday 24 Apr</td><td style="padding-left:15px;">4:00 pm</td></tr><tr><td colspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-left:5px;padding-bottom:5px;"><a href="#" id="events_2749" EventsEventDatesId="2749" LabelId="events_label_1_2749" onfocus="document.getElementById('events_ctl00').value = this.LabelId" onblur="document.getElementById('events_ctl00').value = ''" class="info">The Akmal Show <label id="events_label_1_2749" style="text-decoration:none;">The Akmal Show with Kate Richie Weekdays 4pm-6pm.Akmal was born in Egypt - then moved to Australia. Akmal's mum doesn't think he's that funny - now the rest of Australia think he's ha haa hilarious.</label></a></td></tr><tr><td rowspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-bottom:5px;padding-top:5px;"><img src="../images/greenshd.gif" alt="The IT Road Show.........................." /></td><td style="padding-left:5px;">Wednesday 25 Apr</td><td style="padding-left:15px;">3:30 pm</td></tr><tr><td colspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-left:5px;padding-bottom:5px;"><a href="http://www.nova100.com.au" id="events_3161" EventsEventDatesId="3161" LabelId="events_label_2_3161" onfocus="document.getElementById('events_ctl00').value = this.LabelId" onblur="document.getElementById('events_ctl00').value = ''" class="info">The IT Road Show.......................... </a></td></tr><tr><td rowspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-bottom:5px;padding-top:5px;"><img src="../images/AKMAL_OVER.gif" alt="The Akmal Show" /></td><td style="padding-left:5px;">Wednesday 25 Apr</td><td style="padding-left:15px;">4:00 pm</td></tr><tr><td colspan="2" style="border-bottom-style:None;border-bottom-color:#91907C;border-bottom-width:thin;padding-left:5px;padding-bottom:5px;"><a href="#" id="events_2750" EventsEventDatesId="2750" LabelId="events_label_3_2750" onfocus="document.getElementById('events_ctl00').value = this.LabelId" onblur="document.getElementById('events_ctl00').value = ''" class="info">The Akmal Show <label id="events_label_3_2750" style="text-decoration:none;">The Akmal Show with Kate Richie Weekdays 4pm-6pm.Akmal was born in Egypt - then moved to Australia. Akmal's mum doesn't think he's that funny - now the rest of Australia think he's ha haa hilarious.</label></a></td></tr><tr><td rowspan="2" style="padding-bottom:5px;padding-top:5px;"><img src="../images/redshd.gif" alt="test add 25" /></td><td style="padding-left:5px;">Thursday 26 Apr</td><td style="padding-left:15px;">2:29 pm</td></tr><tr><td colspan="2" style="padding-left:5px;padding-bottom:5px;"><a href="k" id="events_136" EventsEventDatesId="136" LabelId="events_label_4_136" onfocus="document.getElementById('events_ctl00').value = this.LabelId" onblur="document.getElementById('events_ctl00').value = ''" class="info">test add 25 </a></td></tr></table></div></span> <script type="text/javascript">//<![CDATA[Sys.WebForms.PageRequestManager._initialize('ctl06', document.getElementById('form1'));Sys.WebForms.PageRequestManager.getInstance()._updateControls(['tevents$UpdatePanel1'], ['events','events$timer1'], [], 90);//]]></script><script type="text/javascript"><!--Sys.Application.add_init(function() { $create(Sys.UI._Timer, {"enabled":true,"interval":1000,"uniqueID":"events$timer1"}, null, null, $get("events_timer1"));}); Type.registerNamespace('EventsManager'); var prm = Sys.WebForms.PageRequestManager.getInstance(); if (prm != null) { prm.add_endRequest(pageLoadedHandler); } function window.onload() { } function pageLoadedHandler(sender, args) { var hidden = document.getElementById('events_ctl00'); if (hidden != null) { var labelId = hidden.value; if (labelId.length > 0) { var lbl = document.getElementById(labelId); if (lbl != null) { lbl.parentElement.setActive(); } } } } Sys.Application.initialize();// --></script></form> </body></html>

Below is my code for the Render method when I used the endRequest event:

protected override void Render(HtmlTextWriter writer) {base.Render(writer);//Add script and register it. Page.ClientScript.RegisterStartupScript(typeof(EventsManager),"script", @dotnet.itags.org." Type.registerNamespace('EventsManager'); var prm = Sys.WebForms.PageRequestManager.getInstance(); if (prm != null) { prm.add_endRequest(pageLoadedHandler); } function window.onload() { } function pageLoadedHandler(sender, args) { var hidden = document.getElementById('" + ClickedLinkLabelId.ClientID + @dotnet.itags.org."'); if (hidden != null) { var labelId = hidden.value; if (labelId.length > 0) { var lbl = document.getElementById(labelId); if (lbl != null) { lbl.parentElement.setActive(); } } } } ",true); }

Hi,

Can you show me a stripped version of your control and a sample page using it?

It will be easier for us to trouble shooting. Thanks.


Hi Raymond,

I really appreciate your offer of help, but I just figured out what the problem was.

My javascript code below was causing a problem for all the code in my script block on all browsers apart from IE.

Problem code:

function window.onload()
{

}

When I changed it to the code below, it worked in all browsers.

Correct code:

window.onload = function()
{
document.getElementById('" + TimeZoneOffset.ClientID + @."').value = -(new Date().getTimezoneOffset());
}

Thanks again.

pageLoad() javascript function

I understand that a script with the pageLoad() function is a way to hook into the client side load event.

That works great if you are working in the .aspx page itself. What if you're in a user control and want something to hook into the pageLoad() event on the client?

I could use Page.RegisterClientScriptBlock() to inject the JS into the page, but that would overwrite any other function that might be in the master page, content page or other user controls.

Isn't there a way to just add an event to the page load on the client side and not worry about conflicting with other code?

Thanks,

John

Can you give an example of what you're trying to do?


I'm not sure I understand your problem, but if your user control inherits from Sys.UI.Control it's initialize method will be called when the page loads.

You can add your own pageLoad() handler by usingSys.Application.add_load().


HI,

I could use the page_load server event, but that would delay the rendering of the entire page until this process is complete. The effect I am looking for is to render a page so the user has something to look at. Then, when theclient on_load event fires, initiate some long running tasks that can take place while the user already has something to look at.

Thanks,

John


Sys.Application.Load is the client side event, not server side. Take a look at the documentation I linked. That's the event that pageLoad() calls implicitly.


Hi,

In the User control , write this function ,
<script>
function IAMIntheUserControl(object,eventArgs) {
}
</script>

register this script with RegisterClientScriptBlock.

Sys.Application.add_load( IAMIntheUserControl );

PageMethod problems

Hi Everyone -

I have a master page setup, and i would like to use ajax in one of the pages that are to be used as a content page.

In the javascript portion of the detail page, i have some procedures that are marked as webmethods

 [WebMethod()]public void LoadGrid3() {#region LoadGrid3 DataSet ds3 =new DataSet(); DataTable dt3 = ds3.Tables.Add("Customer");

In the javascript side (presentation)

"javascript" type="text/javascript"> function findData() { var request; var AlertDiv = document.getElementById("AlertDiv"); AlertDiv.style.display =""; request = PageMethods.Update(onSearchComplete);} function onSearchComplete(results) { var AlertDiv = document.getElementById("AlertDiv"); AlertDiv.style.display ="none"; alert(results);} function findData_callback(res){ alert("here");}

script language="javascript" type="text/javascript"> function findData() { var request; var AlertDiv = document.getElementById("AlertDiv"); AlertDiv.style.display =""; request = PageMethods.Update(onSearchComplete);} function onSearchComplete(results) { var AlertDiv = document.getElementById("AlertDiv"); AlertDiv.style.display ="none"; alert(results);} function findData_callback(res){ alert("here");} script>

"text/C#" runat="server"> [WebMethod]public void Update() { LoadGrid3(); }

scripttype="text/C#"runat="server">

[WebMethod]

publicvoid Update()

{

LoadGrid3();

}

script>

On the button click event - i have it call the function findData

the PageMethods get popped as an error

Microsoft JScript runtime error: 'PageMethods' is undefined

Am i missing something somewhere??

thanks

tony

Hi,

PageMethods must be declared as public static methods in beta1.

PageMethod problem

HI. I have a problem with calling static PageMethod in asp.net ajax.

Problem apperars then i use UrlMappings. For example i have this code in web.config

<urlMappings>
<add url="~/ComputerManager/WorkstationList.aspx" mappedUrl="~/ComputerManager/ComputerList.aspx?comp_type=1"/>
<add url="~/ComputerManager/ServerList.aspx" mappedUrl="~/ComputerManager/ComputerList.aspx?comp_type=2"/>
</urlMappings>
and this code in ComputerList.aspx. cs
[WebMethod]
public static string SetSelection(string ID,string dataKey,bool state)
{
...
}

so, when call PageMethods.SetSelection(...) a have a error "The server method SetSelection is failed".

post url ends with WorkstationList.aspx/SetSelection

any ideas?

Hi,

You are rewriting your URL, and these URL are fixed one. They don't cater for any extra items or query string parameters. Thats why they don't map to actual page when you want to do that. In this case I will recommend that you add another entry with following items

<urlMappings><add url="~/ComputerManager/WorkstationList.aspx" mappedUrl="~/ComputerManager/ComputerList.aspx?comp_type=1"/><add url="~/ComputerManager/ServerList.aspx" mappedUrl="~/ComputerManager/ComputerList.aspx?comp_type=2"/><add url="~/ComputerManager/WorkstationList.aspx/SetSelection" mappedUrl="~/ComputerManager/ComputerList.aspx?comp_type=1"/><add url="~/ComputerManager/ServerList.aspx/SetSelection" mappedUrl="~/ComputerManager/ComputerList.aspx?comp_type=2"/></urlMappings>

Then i use mappings like you suggested, i get a request to pageComputerList.aspx with parametercomp_type=1, insted of calling PageMethod.

So i rewrite it this way

<urlMappings>
<add url="~/ComputerManager/WorkstationList.aspx" mappedUrl="~/ComputerManager/ComputerList.aspx?comp_type=1"/>
<add url="~/ComputerManager/ServerList.aspx" mappedUrl="~/ComputerManager/ComputerList.aspx?comp_type=2"/>
<add url="~/ComputerManager/WorkstationList.aspx/SetSelection" mappedUrl="~/ComputerManager/ComputerList.aspx/SetSelection"/>
<add url="~/ComputerManager/ServerList.aspx/SetSelection" mappedUrl="~/ComputerManager/ComputerList.aspx/SetSelection"/>
</urlMappings>

and that solves my problem.

Thanks for good idea,ziqbalbh.

PageMethod in the codebehind

I have a method in my codebehind that I would like to call from javascript. My script manager tag has EnablePageMethods="true" and the method in my codebehind is tagged with [WebMethod] and [ScriptMethod]. When I trigger the javascript, I get errors. I've found some things that say that if you want to call a server side method (not in a web service) from your javascript with the PageMethods collection, you have to have that in a script block in your aspx. I've created a script block with a method in my aspx that just calls the function in my codebehind, but I think that's kind of ugly. Is there something I might have just missed that would allow me to just call my codebehind?

Thanks

Here's a code example: http://encosia.com/index.php/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/


Your pagemethod has to be public and static. If that doesn't help, try posting some sample code for us to help debug.


Thanks. That's what I was trying and it didn't work for me. I found some posts around that said that if you wanted to do this, the server side method you were calling had to be in the ASPX. Seemed to fit because of the errors I was getting and the fact that putting a wrapper function in my ASPX for the actual method I wanted to call worked. However, I gave it one more shot this morning (same exact code that didn't work before, I swear) and it's gold.

PageMethod in ASP.NET

Hi

Can anyone tell me what is PageMethod in .NET

How can I implement PageMethod in my Project.

Any help is greatly appreciated.If anybody has link related to PageMethod, please provide me the link...

Thanx

I believe you're refering to a page method, a method contained in the Page class usually used for handling events that happen on or with the page (ie. Page Load, Render, Button Click, etc.)


No..

A PageMethod that is similar to WebService..

The difference is that we dont need to make asmx page for pageMethod.It can be done in your aspx pages

Hope this helps

Thanx


Check this out:

http://www.softsteel.co.uk/tutorials/aspnetajax/lesson4.html


Thanx DotNetGuy121

It helps me but can u give me some more link..

I wanto to use this in my project. So i want to study something more about PageMethods...

Thanx a lot once again

Bye


Use the ASP.NET AJAX DynamicPopulate Extender

Watch a demonstration of using the ASP.NET AJAX DynamicPopulate extender to dynamically populate an area of a web page with the results of an asynchronous call to a web method.

This should help some more.


Hi

Can anyone tell me something more about PageMethod in AJAX

Thanx in advance

Bye


Hi,

Please refer to this article:

http://msdn.microsoft.com/msdnmag/issues/07/01/ExtremeASPNET/default.aspx

Another interesting alternative to building a complete .asmx file for your Web service methods is to embed the Web service methods directly in the page class. If it doesn't make sense to build a complete Web service endpoint for the methods you want to call, you can expose a Web method from your page that is callable from client-side JavaScript by adding a server-side method to your page (either directly in the page or in the codebehind) and annotating it with the WebMethod attribute. You will then be able to invoke it via the client-side object PageMethods. The example in Figure 3 shows the stock quote service sample rewritten to be entirely contained in a single page instead of split into a separate Web service.

Bear in mind that these client-side proxies can only be generated from ASP.NET .asmx endpoints, Windows Communication Foundation .svc endpoints, or WebMethods embedded directly in a page, and are not a general mechanism for calling arbitrary Web services. In fact, there is a general restriction on the underlying XmlHTTPRequest object that requests be restricted to the same domain from which the page was loaded (for security reasons), so this technique could not be used to call arbitrary Web services regardless of whether the client-side proxies supported it. If you do find the need to call external Web services, your best bet is to set up a bridge .asmx endpoint in your own application that calls into a .NET proxy class (generated with wsdl.exe or Add Web Reference in Visual Studio) for the external Web service.

Hope this helps.


Hi

Thanx for the response and time

That would help me

Thanx

PageMethod Exception: "An entry with the same key already exists."

I am calling a PageMethod from a javascript function. This function is called from many different controls on a page. The problem occurs about the second time the method is called. An exception is thrown saying that an entry with the same key already exists. The weird thing is that everything continues to work normally from the users perspective. I would never have noticed this behaviour if I hadn't be debugging. Its more annoying than developement breaking, but I would still like a solution to it. Except I have no idea how to proceed. Am I just using PageMethod improperly?

I'm using ASP.NET 2.0 with C# code.

My config file says this about the assembly I'm using: System.Web.Extensions, Version=1.0.61025.0

Stack trace follows...

EXCEPTION:

{"Error executing child request for /thesite/problemLog.aspx."}

STACK: atSystem.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler,TextWriter writer, Boolean preserveForm, Boolean setPreviousPage,VirtualPath path, VirtualPath filePath, String physPath, Exceptionerror, String queryStringOverride)
at System.Web.HttpServerUtility.Execute(String path, TextWriter writer, Boolean preserveForm)
at System.Web.HttpServerUtility.Transfer(String path, Boolean preserveForm)
at System.Web.HttpServerUtility.Transfer(String path)
at ASP.global_asax.Application_Error(Object sender, EventArgs e) in c:\Projects\Velocity Code\cfdrodeo\Global.asax:line 92
at System.EventHandler.Invoke(Object sender, EventArgs e)
at System.Web.HttpApplication.RaiseOnError()

INNER EXCEPTION:

{"Exception of type 'System.Web.HttpUnhandledException' was thrown."}

STACK:

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)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.problemlog_aspx.ProcessRequest(HttpContext context) inc:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NETFiles\cfdrodeo\0b93ea50\5991e932\App_Web_xczsyy3k.22.cs:line 0
at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandlerhandler, TextWriter writer, Boolean preserveForm, BooleansetPreviousPage, VirtualPath path, VirtualPath filePath, StringphysPath, Exception error, String queryStringOverride)

INNER EXCEPTION:

{"An entry with the same key already exists."}

STACK:

at System.Collections.Specialized.ListDictionary.Add(Object key, Object value)
at System.Web.UI.ClientScriptManager.RegisterScriptBlock(ScriptKey key, String script, ListDictionary& scriptBlocks, ArrayList& scriptList, Boolean needsScriptTags, Boolean& inScriptBlock)
at System.Web.UI.ClientScriptManager.RegisterScriptBlock(ScriptKey key, String script, ClientAPIRegisterType type)
at System.Web.UI.ClientScriptManager.RegisterClientScriptInclude(Type type, String key, String url)
at System.Web.UI.ScriptRegistrationManager.RegisterClientScriptInclude(Control control, Type type, String key, String url)
at System.Web.UI.ScriptManager.RegisterClientScriptInclude(Control control, Type type, String key, String url)
at System.Web.UI.ScriptManager.RegisterClientScriptIncludeInternal(Control control, Type type, String key, String url)
at System.Web.UI.ScriptManager.RegisterScripts()
at System.Web.UI.ScriptManager.OnPagePreRenderComplete(Object sender, EventArgs e)
at System.Web.UI.Page.OnPreRenderComplete(EventArgs e)
at System.Web.UI.Page.PerformPreRenderComplete()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

Thank you for your help.

Hi,

could you post the code of your page method and the JavaScript code that you use to invoke it?

PageMethod Context parameter

var context = new Array()

I am trying to invoke PageMethod.DoSomething(parameter1, parameter2, OnSucceeded, null,null,null,context)

so context is an array

But in the OnSucceeded(result,response,context) the context parameter contains the name of the page and the method called. It is not returning back the context that I called it with.

Any help will be greatly appreciated.

Thanks

Try to?take?a?look?at?this?blog?about?how?to?use?PageMethod?in?Ajax?RC?1.0?-?http://blogs.gotdotnet.com/robj/archive/2007/01/05/pagemethods-in-asp-net-ajax-1-0-rc.aspx
Wish this can help you.

PageMethod Code Caching

Hi,

When I change the code of my pagemethod, I have to run IISRESET for the new code to take affect.
If I don't, then the old code is still executed. Building the page or the project doesn't help either.

Any ideas?

Are you sure it's not just caching the js proxy in your browser?

Yes, I'm sure.

I did some more testing. Seems that building the whole project again is actually enough to get the new code to be excuted. (so iisreset not required). But building the page on itself is not enough.


Interesting. i would've expected <compilation debug='true' /> to be enough to force the rebuild per change. I wonder if there's some level of page caching set up in the machine.config?


hello,I am experiencing the same problem.

http://forums.asp.net/thread/1668850.aspx

don't give up on this!

PageMethod calls are not asynchronous

I created a test app to try out the PageMethod functionality. I can make four calls to a PageMethod and I can verify that they are called asynchronously via the tracing statements. So I moved the test page into an existing website that I converted to AJAX and it appears that the methods are call synchronously. Is there a setting somewhere that I might be missing? It is the exact same page in both sites. Any suggestions are greatly appreciated. I've included the log results and methods for reference.

Test App Trace (This is the expected result. Notice that all of the "In Server Method" entries occur before any of the "Out Server Method" entries):

Post PageMethodsfor 1Post PageMethodsfor 2Post PageMethodsfor 3Post PageMethodsfor 4In Server Method: 1 - 633088835535430360In Server Method: 2 - 633088835538237248In Server Method: 3 - 633088835543249548In Server Method: 4 - 633088835548261848Out Server Method: 4 - 633088835573122856Out Server Method: 3 - 633088835578335648Out Server Method: 2 - 633088835590766152Out Server Method: 1 - 633088835600089030

Converted App Trace(This is not the expected result. Notice that the "In Server Method" entries alternate with the "Out Server Method" entries):

Post PageMethodsfor 1
Post PageMethodsfor 2
Post PageMethodsfor 3
Post PageMethodsfor 4
In Server Method: 1 - 633088837286126504
Out Server Method: 1 - 633088837375044706
In Server Method: 2 - 633088837378352824
Out Server Method: 2 - 633088837407023180
In Server Method: 3 - 633088837408627116
Out Server Method: 3 - 633088837421057620
In Server Method: 4 - 633088837423664016
Out Server Method: 4 - 633088837477596364

Server Method:

 [WebMethod]public static int GetHitCount(int grid) { Debug.WriteLine("In Server Method: " + grid.ToString() +" - " + DateTime.Now.Ticks.ToString());int sleep = rand.Next(1000, 10000); System.Threading.Thread.Sleep(sleep); // Sleep to slow down the process Debug.WriteLine("Out Server Method: " + grid.ToString() +" - " + DateTime.Now.Ticks.ToString());return rand.Next(1, 100); }

Client Methods:

function GetAllData() { PageMethodCall(1); PageMethodCall(2); PageMethodCall(3); PageMethodCall(4); } function PageMethodCall(context) { var waitImg = document.getElementById("imgWait" + context); waitImg.style.visibility =''; PageMethods.GetHitCount(context,OnSucceeded, OnError, context); Sys.Debug.trace('Post PageMethods for ' + context); }

Ok, I still don't have a good solution but I've found the problem. Though a process of elimination, I've determined that the existance of a Global.asax file is causing the problem. When I got into my test project and select "Add New Item" -> "Global Application Class", the request begin to queue. I have made no changes to the Global.asax.

Hi there, this is some kind of combined issue. -- It's about the session access. Strange ,right? What you can try is to set "enableSessionState="false|ReadOnly", the request is executed asyncronously. But as long as you change to true which is the default, your requests are piped up.

Note, the pipe-up behavior only happens for the requests from the same browser. If you have two browsers, it is always executed asyncronously.

The things that I haven't found out is where this crappy logic is. If you take a look at the system generated global.asax.cs , it is quite clean. I guess it is somewhere in HttpApplication which is the base class.

Hope this could help a bit.


Access to Session state variables must be performed synchronously. You can either set EnableSessionState to false or readonly, or you can use a different session state provider that allows asynchronous access to state variables.

PageMethods and NON-Static methods

OK, after 4 days of trying every possible combination of everything... I *finally* figured out how to get PageMethods to work. The myth of "it can't be in the code behind" is completely wrong, however I'm starting to see that "the method but be static" is NOT a myth.

How in the world am I supposed to update the GridView then?

Your first response should be ...


<asp:UpdatePanel ID="upComparisonData" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnComparisonNavigate" EventName="Click" />
</Triggers>


That's beautiful... works great... BUT... I need to do more than merely update. I can't just update, there's some purely client-side custom validation I *MUST* do. There are many components on this application which were created in purely client-side XHTML and ECMAScript DOM. The above code will NOT work for me because I have to set all kinds of status bars, check other services (non-Atlas), and do validation as well as flip the status of quite a few objects around (turn DIVs on, turn DIVs off... etc...)... I mean there's a bunch of stuff going on in this app.

So... how in the WORLD do I access a GridView in my page from a static method? I have no problem with writing this entire thing custom... that's childs play, but I would much rather do this in Atlas so other developers don't have to try to decode my ninja Ajax code.

"The myth of "it can't be in the code behind" is completely wrong"

it wasn't a myth on earlier versions (beta 1 i believe) and probably has been fixed in the two releases since then, hence the "myth" is no more


Good deal..

Anyone know if THIS *critical* design flaw has been fixed?


If everything you're doing is purely client-side, then instead of trying to use PageMethods to update your panel, just put a display:none button in your UpdatePanel and call it's .click() from the clientside:

$get(

'ctl00_bBinHist').click();

That causes a postback, even in the UpdatePanel (which obviously defeats the entire purpose of the UpdatePanel). This entire application has absolutely NO postbacks. I'm not about to add one now.

I worked around that situation by rewriting a TON... now I have another situation which a rewrite is simply not possible.


try:

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(PageLoadedEventHandler);
function PageLoadedEventHandler() {
// custom script
}
</script>

this will be execute after updatePanel... ;-)


hello.

well, if you're chaging UI during a partial request, you do really need to use an updatepanel. if you only need to check for values, why not pass them from the client to server as method parameters?
That's obvious... of course you need an UpdatePanel, but I'm not going to use triggers... that is completely useless.

What? I'm confused... how does that update a GridView on a whim?

I simply want to update a control from ECMAScript. There are many things that our library does to the application, so giving ALL the control to Atlas would be pointless. I need something that will allow a control to be updates via a simple client-side call, not a trigger which doesn't allow your own manipulations, or the useless PageMethods which in no way allows for updating of controls.

For now I'm just going to do this manually... have an ASPX page with the GridView and have an XmlHttp call to the page and do a screenscrape of the control, do a simple DOM parse, and DOM child. Not that difficult... I was just hoping Atlas did this for you as not everyone who works on this application knows Ajax programming as well as I do.

PageMethods and Exceptions

Hi,
i was looking for information about how to manage Exception throwed by page methods.
I mean, is there any way in the javascript function that is called on failure of the page method to know the type of the exception throwed?
I know that the object passed as parameter to this function has the get_message() method to get the exception's message, but i can't find any other information about it.

sorry for my poor english and thanks for your answers,

bye

Well, frankly your best option is to not throw them. Either handle them inside the page method or else have some kind of catchall error handler for the page / app (or both). In terms of debugging, you can then (in the catch block) log on the server any info you might want to, and not worry about whether the javascript object will support inspection of the core problem or not.


Say you call a page method like this:
function UpdateTime()
{
PageMethods.GetCurrentDate(OnSucceeded, OnFailed);
}
function OnSucceeded(result, userContext, methodName)
{
$get('Label1').innerHTML = result;
}
function OnFailed(error, userContext, methodName)
{
$get('Label1').innerHTML = "An error occured.";
}

OnFailed will be called anytime there's an exception thrown from the web method. "error" contains several useful properties, such as error._exceptionType, error._message, and error_stackTrace.


FYI the Exception Type, StackTrace etc is not the server side objects, instead it is the client info.


gt1329a:

"error" contains several useful properties, such aserror._exceptionType, error._message, and error_stackTrace.

thank you, this is what i was looking for!

but before i mark this thread as "resolved" there's another question a want to ask you:

where did u find those information? 'cause i look for them for pretty long time but i culdn't find anything but the get_message() method.


Checkouthttp://www.asp.net/ajax/documentation/live/ClientReference/Global/JavascriptTypeExtensions/ErrorTypeExt/default.aspx andhttp://msdn2.microsoft.com/en-us/library/b8664205-d28e-4cde-bd76-69173ff72dea.aspx


thanks a lot to all of you


YaWW:

where did u find those information? 'cause i look for them for pretty long time but i culdn't find anything but the get_message() method.

I find it easier toexplore the DOM with a JavaScript debugger, than to read the docs. That's how I found the exception information. I set a breakpoint on the client side error handler and then looked at what information was returned.

PageMethods (which are static) and access Session from them ?

Since PageMethods are static if I need the access to the Session how should I go about it ?.

One straightforward way may be to add a field in my (Page) class like this

public partialclass MyPage : Page {private static MyPage _p;protected void Page_Load(object sender, EventArgs e){ _p =this; } [ScriptMethod][WebMethod]public static void MyPageMethod(string contextKey){int a = (int)_p.Request.Session["myintval"]; } }
Do you guys thinking this is the only and best way to do it ?.
Please suggest.

Regards & thanks

Kapil

you could do it in more simple way:

instead of

int a = (int)_p.Request.Session["myintval"];

int a = (int) HttpContext.Current.Session["myintval"];

The static property Current of HttpContext is accessible from everywhere.

Cheers,

Yani


An even better solution would be to implement a facade pattern for your session (more infohere).

Regardless of anything else you do in terms of code style and whatnot, you have to change your WebMethodAttribute to

[WebMethod(EnableSession=true)]


silly me, huh. I knew I was doing something wrong.

Thanks for the answer Yani

Regards

Kapil

PageMethods

Hi Folks

I'm getting an error with AJAX Beta1 trying to access PageMethods...

function beginImport() { disableButton('btnSubmit'); displayProgress(); updateText('Importing Translations, please wait for process to complete before clicking anything!'); PageMethods.Import(onImportComplete); }

Causes this error...

Error: PageMethods is undefined

Are you defining the onImportComplete function in Jscript?

I have the same problem. I keep getting "PageMethods is not defined" error. Here's my code:

<%@. Page Language="C#" AutoEventWireup="true" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><title>Untitled</title><script runat="server"> [System.Web.Services.WebMethod] public string GetMessage() { return "Hello World"; }</script></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <a href="#" onclick="javascript:preview();">Test</a> <script type="text/javascript" language="javascript"> function preview() { PageMethods.GetMessage(onComplete); } function onComplete(res) { alert(res); } </script> </form></body></html>

Shawn Burke talks about PageMethods and Ajax Beta in hisblog

It seems that they need to be static and marked with the ScriptMethod attribute. But if PageMethods are static how do we access page control values within such a method?


I am completely stuck on the pagemethods, and having the same problem. I have read the blog and added the [ScriptMethod] tag to the page method (this tag is not in Microsoft's pagemethod tutorial (here), but I am willing to try anything at this point). I have used the default web.config file that is created when you use the ASP.NET AJAX CTP - Enabled Website template in VS2005, and verified that all of the settings are present as outlined in the migration white paper and the webservice tutorial on ajax.asp.net.

I need to be able to call a pagemethod because i need access to the viewstate and server control properties on the page. A webservice would not give these to me.

All of this worked fine in the July CTP... here is my code:

[C#]

[WebMethod]
[Microsoft.Web.Script.Services.ScriptMethod]
publicstatic GeneralLiability.GeneralLiabilityQuote GetQuote()
{
returnnew GeneralLiability.GeneralLiabilityQuote(10);
}

[JS]

Rate:function()
{
this.showLoadingPanel();
this._MustRefresh.set_visible(false);
// should be page method
PageMethods.GetQuote(this.onGetQuoteComplete, this.onGetQuoteTimeOut);
},

[ScriptManager]

<asp:ScriptManagerID="ScriptManager1"ScriptMode="Debug"runat="server">
<Scripts>
<asp:ScriptReferenceAssembly="Microsoft.Web.Preview"Name="Microsoft.Web.Resources.ScriptLibrary.PreviewScript.js"/>
<asp:ScriptReferenceAssembly="Microsoft.Web.Preview"Name="Microsoft.Web.Resources.ScriptLibrary.PreviewGlitz.js"/>
<asp:ScriptReferenceAssembly="Microsoft.Web.Preview"Name="Microsoft.Web.Resources.ScriptLibrary.PreviewDragDrop.js"/>
</Scripts>
<Services>
// ths webservice is a work around until i get the PageMethod working
<asp:ServiceReferencePath="~/WebServices/RateWebService.asmx"/>
</Services>
</asp:ScriptManager>


Spent alittle more time looking at the PageMethods issue.

I wrote a small test app and realized that the PageMethods object exists when the webmethod is included in the aspx file (as long as I added the
[Microsoft.Web.Script.Services.ScriptMethod]) attribute, but when I move it to the code-behind file, it gives me the undefined error... which leads me to question... are pagemethods no longer allowed in the code-behind file?

Anyone?


See:http://blogs.msdn.com/sburke/archive/2006/10/21/hint-components-that-use-web-services-with-asp-net-ajax-v1-0-beta.aspx. PageMethods are broken in Beta1 and do not work in code behind.

Dimitrod, you say: "But if PageMethods are static how do we access page control values within such a method?".
I may be wrong, but IMO it does not make sense to access controls in PageMethods. PageMethods are part of the business layer. You should read control values using client-side code, pass these values to the method as parameters and read the returned data in the form of a basic type or a complex serialized object. I personally think it is a good thing that PageMethods are now static.


In the Atlas July CTP, Im using the Page.User.Identity.Name as a security verification inside the PageMethods , How would I do this in the new version without passing parameters in javascript, as this would reveal the values.

>> I may be wrong, but IMO it does not make sense to access controls in PageMethods. PageMethods are part of the business layer.

Yes and no. But the point is you can already achieve teh 'business layer' effect by calling a Web Service and now with PageMethods being forced to be static you're doing nothing but duplicating that functionality. All this does give you another place to store your 'service methods'.

Allowing access to the page is very valuable IMHO because it allows you to read values set on the client without having to pass every damn field value as a parameter or as part of an object you first populate on the client.

Consider this: You have a form with 50 input fields on it and the user fills that out. Now you want to use AJAX to save those values. If you use PageMethods or Web Service you have to pass 50 parameters or create a client object that first parses the values out of the fields, possibly converts to the proper types etc. Then you send the data to the server, and you get the parse the values AGAIN on the server - out of the parameters or object into a business object or a DataRow or whatever.

Instead not passing parameters but receiving the values from the client directly on the server in the POST buffer lets you deal with the input values once and store it directly into your object.

I can be a huge timesaver and reduces boatloads of error prone $get() statements on the client.

If all that PageMethods does is duplicate Web/SCript Service behavior but in a page I say cut the whole thing and take the overhead out of the Page class.


Page.User is merely a convenience property that wrapsSystem.Threading.Thread.CurrentPrincipal, which is static, so just access that instead :)


Rick,

Convincing point of view, although a form with 50 input fields seems theoretical to me because it is not very user friendly. I should not have said "it does not makes sense" but I still do not like it.

Despite the fact that you definitely have a point, I prefer the more stateless approach of parsing the fields on the client and feeding a Javascript object that is passed to the web service or page method as you describe. Contrary to what you say, it is not needed to parse the object again on the server, the ASP.NET Ajax layer does that automatically for you, although you may have to write a couple of converters. Note that my business objects are very light data structures which are effectively persisted by business brokers.

By the way, thank you for your valuable web site, which I often consult.


I agree as well - in most cases I use Web Services to abstract the logic, because it's just cleaner. But I would very much like to have the option to be able to get at the data in an easier way in the page.

As to the form with 50 fields: Well there's lots of ways to represent data <s>. Yeah you're probably right but I have a couple of forms that have this much data in various pages of a tabbed interface that's driven through AJAX. In fact in a properly architected AJAX application values are probably updated more frequently than one giant form submit.

But even so even if you have a smallish form like this:

http://www.west-wind.com/atlas/CustomerList/AtlasCustomerList.aspx

You then have code like this to retrieve the data to send to the server:

// *** Cheating: This object contains only strings!
// If other types exist conversion
// must be done here.
Customer.Companyname = GetValue('txtCompany');
Customer.Contactname = GetValue('txtContactName');
Customer.Address = GetValue('txtAddress');
Customer.City = GetValue('txtCity');
Customer.Postalcode = GetValue('txtPostalCode');
Customer.Region = GetValue('txtRegion');
Customer.Country = GetValue('txtCountry');

// *** Pass back the customer object to the server
CustomerService.SaveCustomer(Customer,SaveCustomerCallback,ErrorCallback,ErrorCallback);

It gets worse if the object your setting values on has typed values - then you have to do type conversion in JavaScript which is no fun... Then on the server you do that parsing again out of the object so you're just duplicating the work.

When I meant 'parsing on the server' I didn't mean parse the object. You do get the object back on teh server. But it's a proxy at best and from there you have to move the data out into a real object that actually does the data logic - an Entity that can save or a DataRow or whatever it may be. For most types a type converter isn't even required as the JSON proxy creates the required proxy objects on the client for you. That is very cool, but it's still more work than it has to be - you're still 'reading' the data twice - once on the client, then again on the server. Instead you could do it once and be done with it.


As something of an ASP.NET AJAX Novice I find this thread very interesting.

For me it touches a wider issue which is that for the newbie there is a vast array of possible approaches to building an ASP.NET AJAX app and the best path is not always clear.

My very first app simply used an UpdatePanel and seemed to work fine but then I decided I wanted a bit more control over what was happening.

Consequently my next app used PageMethods to call functions in the ASP.NET Codebehind. Again this seemed to work fine for such things as retrieving Strings etc.

Then I looked at Web Services and devised a couple of those which I then referenced from my ASPX pages (using the ScriptManager)

Now though I'm not really very clear where to go next.

I guess it's like anything else, you just need to give it time and try lots of different things before you can make a judgement call on the best way forward. The danger is that for those of us who have never used much javascript, we may be tempted to try and avoid it (using the UpdatePanels etc) but then come unstuck when we want a bit more control over our app's behaviour.

I hope the documentation will help with this though once the framework goes RTM.


I think ScriptMethods (PageMethods) are part of the UI layer; consider where they are declared - no business logic should be residing in the Page class. I hope they change it so that they'll go back to being state-aware and part of the Page lifecycle again. The way it's implemented in the new beta, there's really not much distinction between a ScriptMethod and a WebMethod (web service) any more.

insted of breaking ypur head and program again and again

it is better to wait to next version or final version

i will stick in july ctp until a better version will come

my program need page.clientscript.registerStartupscript and PageMethod

and both of them not working in ajax beta 1

so why go ther from july ctp?