Showing posts with label page. Show all posts
Showing posts with label page. Show all posts

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 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_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?

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

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

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 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?

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.

PageMethod Timeout

Hi

I call a web method exposed in an aspx page as follows:

PageMethods.MyWS("hello world",
OnCallbackComplete,
OnCallbackTimeout,
OnCallbackError,
null,
10); // timeoutInterval

To simulate the timeout I add some sleep time to the thread in the web method, lets say 10000 (10 seconds). Problem is the timeout callback method on the client doesn't get invoked.

Any ideas?

CraigThere was a bug where we weren't respecting the timeoutInterval set onthe request if the default timeout interval is set. Can you checkif you have set the WebRequestManager's timeout interval? Trysetting the WebRequestManager's timeout interval and see if thattriggers the timeout callback...

Hope that helps,
-Hao

Thanks for the reply.

I tried the following which didn't trigger the timeout as expected:

Sys.Net._WebRequestManager._timeoutInterval = 10;

Sys.Net._WebRequestManager.timeoutInterval = 10;

Sys.Net._WebRequestManager.set_timeoutInterval(10); // threw an exception

PageMethods.MyWS("hello world",
OnCallbackComplete,
OnCallbackTimeout,
OnCallbackError);
So that's not quite right, the instance you want to use is the static Sys.Net.WebRequestManager, rather than the _ one.

So you can do Sys.Net.WebRequestManager.set_timeoutInterval(10), or in the xml markup, you can do something like

<script type="text/xml-script">
<page xmlns:script="http://schemas.microsoft.com/xml-script/2005">
<components>
<webRequestManager timeoutInterval="3000"/>
</components>
</page>
</script
Hope that helps,
-Hao

that did the trickBig Smile [:D]

thanks

PageMethod Static Ajax WebService and User Controls

I have a page HostPage.aspx, which is a generic hostpage that will dynamically load Web User Controls at runtime, according to the needs of various other users. Those other Web User Controls will be created by the other users, such that they can put anything they like in that Web User Control, and it will be dynamically populated and put in the HostPage.aspx. They will always use HostPage.aspx, they cannot edit it. This is working as-is, and everything is great.

Now, some users want to put AJAX functionality in their User Controls, such that the HostPage.aspx will contain their User Control, the User Control will contain an UpdatePanel, a ScriptManager, etc.

To enable page methods, we have to set the EnablePageMethods="true" on the scriptmanager, and have to declare a static method *somewhere*. The requirements are such that we cannot be declaring these static methods in the HostPage.aspx, because it cannot know what the controls, and therefore static methods, are until runtime. On the other hand, if we declare these static methods in the User Control, it's not defined in the HostPage, and AJAX PageMethod callbacks fail ("Method myMethod is not defined"), because the page doesn't know of it's existence.

1. Has anyone tried to do something similar to this, namely having AJAX controls in a User Control, which is hosted in a page, yet also needs to use the Page Methods, yet cannot declare them in the page (I know, that's pretty specific).

2. Any ideas on how this might be accomplished?

I'm thinking of using Reflection or DynamicMethod (http://msdn2.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx) to make this happen, such that at runtime, the page will examine its child controls for any static methods with the ScriptService attribute, and then dynamically create a static method on itself with the same name, calling the child, but that is rather involved and I fear the performance risk of this (if this whole idea is even possible). Plus, the generated method wouldn't exist until after the controls exist, and I'm not sure where that falls in relation to the timing of the AJAX extensions (looking for the MethodName). It might be (probable) that the handler is looking for the method even before the controls are initialized, in which case that idea won't fly.

You can't do that... as described here (http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx) Page Methods are only on pages :)

But you can get what you want if you make your user control register a "web service" as in this article:http://www.singingeels.com/Articles/Consuming_Web_Services_With_ASPNET_AJAX.aspx

If your users aren't able to add webserivces (I really don't know the situation your building)... then they can register a regular old "AsyncPostBack" and wire it up themselves (sorry, no article on that yet).


Right, I understand completely the concept of PageMethods, that they are on pages, etc. That's why this is a bit of a tricky spot.

I guess what I'm looking for is whether anyone has come up with anything clever to get around this situation (PageMethods from a Usercontrol). The usersare free to create and consume their own webservices, if they like, but if possible, I would like to give them this functionality for this situation.


OK, I believe it's Page.ClientScript.RegisterAsyncPostBack or maybe ScriptManager.RegisterAsycnPostBack ( I can't remember )... either way, it'll post back to the page... and ultimately the user control, and fire an event (on the user control).

That'll work just like the page methods... (a little better actually for what you're doing)

PageMethods dont regenerate on file change?

If I define a new page method or change an existing page method I have to restart my dev asp.net server to see the change in the generated javascript (page prototype)? anyone else having this problem?

thanks

Hi,

Without any valuable information, it is hard to say where the problem lies on.

Please provide any more information,eg. any code of this.

Thanks!


Hi Craigw,

It seems like a cache issue rather than a IIS issue. So I suggest you to save your web.config file without any modifications and have a test. If it works, we can confirm it.

Also you can delete all the cache file or do the following steps. open the IE -->Tools-->Internet Options-->General Dialog-->Browswer History-->Settings-->select "Every time I visit the webpage".

I hope this help. If it doesn't work, please feel free to let me know with more information.

Best regards,

Jonathan


This problem has been quite annoying for some time. Can you please confirm if it has been identified and whether a fix will be available?

It happens on the server (Win 2003 R2) as well as on developer PCs (Cassini). Restarting the web server does the trick as well as re-saving web.config. It's quite easy to reproduce (and yes, I have enbaled PageMethods in the ScriptService tag...)

PageMethods call from user controls (ascx)

Hello,

i am looking for a way to call webmethods defined in an (ascx) user control (not a web form page aspx) using PageMethods.{MethodName}. For now, i only get a javascript error saying that PageMethods is not defined. Is there a different syntax to acces thos methods or is it just not possible ?

Thank you for your help

thomas

Any answer would be appreciated.

Thank you

thomas


hello.

currently, you can only call web service methods or page methods (and in this case, the methods must be static)

PageMethods call - Authentication Failed.

Hello,
I am working with RC1 and am having problems calling a pagemethod. It keeps telling me Authentication failed. 
My page is using a master page where the Scriptmanager is declared. As you can see I am using a ScriptmanagerProxy on my main page.
The code works fine when forms authentication is not on and everything else on the site works fine when Authentication is on except Ajax pagemethod calls.
Authentication is occurring on my login in page and all of the Athentication is builtinto the codebehinds. My Question. Do I have to implement
Sys.Services.AuthenticationService to be allowed to call an Ajax web service call or pageMethod call when usingFormsAuthenication?
 Here is an incomplete example of what I am trying to do. Missing the login page
// java script file test.jsfunction pageLoad(sender, eventArgs){ PageMethods.TestThis("bar",onTestComplete, OnTestFail);} 
function onTestComplete(result){ alert(result);} function OnTestFail(error){ alert(error._message)}
// code behind[WebMethod]public static string TestThis(string name){return"foo " + name;}
 
<!-- web config --><system.web><authentication mode="Forms"><forms name="test" loginUrl="Login.aspx" protection="All" timeout="60" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="Default.aspx" cookieless="UseDeviceProfile" enableCrossAppRedirects="true"/></authentication><authorization><deny users="?"></deny><allow users="*"/></authorization></system.web><!-- html page --><asp:ScriptManagerProxy id="ScriptManagerProxy1" runat="server"> <SCRIPTS> <asp:ScriptReference Name="PreviewScript.js" Assembly="Microsoft.Web.Preview> <asp:ScriptReference Path="Scripts/test.js" ScriptMode="Debug"'> </SCRIPTS> <SERVICES> </SERVICES></asp:ScriptManagerProxy>
"Debug"'>Can someone please help me??
"Debug"'>Thanks in advance. 
"Debug"'> 

Ok, Im gonna guess that its probably becasue the pageMethod has to be defined as static, if so is there a workaround?

Or are pageMethods totally useless in site with forms authentication?


Try changing your pagemethod's WebMethod attribute to be: [WebMethod(Session=true)]. That should help w/ the authentication issue.

Monday, March 26, 2012

PageMethods is undefined

Hi there

I have a simple page that calls a server side page method via the scriptmanager / page methods detailed on this site. This has worked fine recently when until I updated our dev team to use the new asp.net ajax 1.0.

Once I'd updated my web.config as per the doco all works fine on my pc but on all others when I call the server side method I get the client script error " PageMethods Is 'Undefined' ". I am sure this is an environmental issue but I would appreciate any tips on how to figure out what is going on!

To update one of the boxes (eg our test server) I did the following steps.

    Uninstall previous ASP.net Ajax (RC1)Install new versionUpdate web.config as per instructions in the doco

Here is my source code

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="AddNote.aspx.cs" Inherits="controls_AddNote" EnableViewState="true" %><%@dotnet.itags.org. Import Namespace="System.Web.Services" %><!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 id="Head1" runat="server"> <title>Add a note to this cell</title> <link rel="stylesheet" type="text/css" href="../css/calumo default.css" /> </head> <body leftmargin="0" rightmargin="0" topmargin="0" bottommargin="0"> <script type="text/javascript" language="javascript"> function PageMethodCall() { var TicketId=parseInt($get("inpTicketId").value); var DataSource=$get("inpDataSrc").value; var Catalog=$get("inpCatalog").value; var Cube=$get("inpCube").value; var DataPointMdx=$get("inpMdx").value; var NoteValue=$get("taNote").value; if(NoteValue.length>0) PageMethods.SendNote(TicketId,DataSource,Catalog,Cube,DataPointMdx,NoteValue,OnSucceeded); } // This is the callback function // that process the page method call // return value. function OnSucceeded(result) { // Display the result. if(result==1) window.close(); else alert("Calumo Server Exception:-" + result); } function Validate() { if($get("taNote").innerText.length>0) $get("btnSend").value="Send"; else $get("btnSend").value="Close"; } </script> <form id="frmAddNote" runat="server" target="_self"><asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <input runat="server" type="hidden" id="inpTicketId" value="" /> <input runat="server" type="hidden" id="inpDataSrc" value="" /> <input runat="server" type="hidden" id="inpCatalog" value="" /> <input runat="server" type="hidden" id="inpCube" value="" /> <input runat="server" type="hidden" id="inpMdx" value="" /> <table id="Table1" runat="server" height="100%" width="95%" cellpadding="0" cellspacing="0"> <tr id="trHeader" > <td><img alt="" src="../images/Calumo/top_bar.jpg"/></td> </tr> <tr><td> </td></tr> <tr id="trBody"> <td id="tdNoteArea" align="center">  <textarea cols="10" runat="server" style="height:100%;width:650px;" id="taNote" rows="10" ></textarea> </td> </tr> <tr><td> </td></tr> <tr id="trFooter"> <td style="padding-right:20px;width:100%" id="tdClose" align="right"> <input id="btnSend" type="button" value="Send" onclick="javascript:PageMethodCall();" /> </td> </tr> </table> </form> </body></html>

and here is the server code

 [WebMethod()]public static string SendNote(int TicketId,string DataSource,string Catalog,string Cube,string DataPointMdx,string NoteValue) {try {// Add a note to the server code and return a sample msgreturn"It Works"; }catch(Exception ex) {return ex.Message; } }

Any hints on troubleshooting would be greatly appreciated

Thanks in advance

Graham

Try settingEnablePageMethods="true"

<

asp:ScriptManagerID="ScriptManager1"runat="server"EnablePageMethods="true">

Yep thats it! Would probably be a good idea to add to the update doco

thanks


Was that missing in the documentation somewhere? We'll happily fix it... just point me to where it's missing.


There should probably be a section on Page Methods...in the docs that is accessible by the left hand side index..

Also, for whatever reason - the UpdatePanels UpdateMode is set by default to "Always" a special highlight in the docs should indicate this is the default and to change it to conditional for partial rendering / asynchronous updates. I was kinda surprised when investigating some of the post and issues on always full postbacks - that when I just dragged and dropped an updatepanel in designer - it defaulted to "Always"... kinda missing the purpose I think as if you are releasing this - then the default should err on side of the Ajax technology it is supposed to provide and this is a change I think from the RCs but not positive as I always declare everything anyways... but alot of folks just drag and drop and assume they are getting the settings for exploiting the Ajax enviroment...


I followed this docohttp://ajax.asp.net/documentation/Migration_Guide_RC_to_RTM.aspx

and unless I skipped over it I didn't find any reference to the EnablePageMethods

thanks again


I agree! Where can you find reference and documentation to PageMethods ? I use the block of code on this post as my reference right now ..


http://ajax.asp.net/docs/tutorials/ExposingWebServicesToAJAXTutorial.aspx

I agree this would be nice to see in the "differences" docs. I'll see if it can be added.


Just wanted to say thanks, all.

I was trying to get a method to run from a page (both in the .aspx file and in the code behind) and kept getting the js error of "PageMethods" not found. Adding that attribute to the ScriptManager cured the problem.

Pete.

PageMethods is undefined

When using the July CTP, I was able to use the PageMethods defined in my web page with no problems.

After loading the beta 1.0 release, I get the error "PageMethods is undefined" when attempting to use WebMethods from my page.

The "Change from the CTP" docs mention that this has been changed to use static page methods and that it's supposed to be easier now. It would be very helpful to see a working sample using PageMethods in the most recent beta release.

Anyone have a working sample?

Ken

hello.

here's a quick test i've written

<%@. Page Language="C#" %>
<%@. Import namespace="LivroAtlas"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
[System.Web.Services.WebMethod]
public static Aluno[] ObtemAlunos()
{
Aluno[] alunos = new Aluno[]{
new Aluno( "João", 15 ),
new Aluno( "Rita", 16 ),
};

return alunos;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="manager" />
<input type="button" value="invocar método da página" onclick="handle()" />
</form>
<script type="text/javascript">
function handle()
{
PageMethods.ObtemAlunos( handleCallback);
}
function handleCallback( res )
{
for( var i = 0; i < res.length; i++ )
{
alert( res[i].Nome + "-" + res[i].Idade );
}
}
</script>
</body>
</html>


Thanks very much, Luis.

I had missed that page methods are now required to be static.

Ken


Could someone please bring back the old PageMethods, when it could access the page control's value, that was great.

hello.

use updatepanels for that and set the childrenastrigger to false so that you don't send back html to the client. there's no need to have pagemethods without them being static.can anyone provide a good scenario where non-static page methods are really the only way to go?


I'm actually using the PageMethod object so that when a user presses an image button, it calls a server side method that pulls values out of session state as well as control values and then makes a call to a back end software that does some processing for our application and returns an object that we then load into a treeview. However, you are not able to reference Session variables from static methods neither are you able to reference controls. This is my example...do you think i'm doing it wrong or do I have a valid scenario?

hello.

how about using an updatepanel or a web method? you do say that you need to refresh the UI...btw, i do think that you can access session state from a static method:

<%@. 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">
[System.Web.Services.WebMethod]
public static int O()
{
HttpContext ctx = HttpContext.Current;
ctx.Session["i"] = Convert.ToInt32(ctx.Session["i"]) + 1;
return Convert.ToInt32( ctx.Session["i"] );
}

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);

if (!this.IsPostBack)
{
HttpContext ctx = HttpContext.Current;
ctx.Session["i"] = 0;
}
}
</script
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="manager" />
<div>
<input type="button" runat="server" id="bt" onclick="handleClick()" />
</div>
</form>
<script type="text/javascript">
function handleClick()
{
PageMethods.O(function(res){ alert( res ); });
}

</script>
</body>
</html>

that sample simple returns an int. maybe you can adapt it so that it returns what you need.


This is odd, but I can't seem to get PageMethods to call when the WebMethod is in a codefile. I didn't have a problem with that before. Any thoughts? The exact same code works fine if the WebMethod is part of C# embedded on the page in script tags as Luis has done. I really prefer it the way I had it before, as I prefer using codefiles.

"C#"-->"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"> [System.Web.Services.WebMethod] public static string Test() { return "Success"; }</script><html xmlns="http://www.w3.org/1999/xhtml" >"Head1" runat="server"> "form1" runat="server"> "server" ID="manager"> "button"value="invocar método da página" onclick="handle()"> "text/javascript"> function handle() { PageMethods.Test(handleCallback); } function handleCallback( res ) { alert( res ); }

On the other hand, it doesn't work like this:

"C#" AutoEventWireup='false' CodeFile="Default.aspx.cs" Inherits="_Default"-->"-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >"Head1" runat="server"> "form1" runat="server"> "server" ID="manager"> "button"value="invocar método da página" onclick="handle()"> "text/javascript"> function handle() { PageMethods.Test(handleCallback); } function handleCallback( res ) { alert( res ); }using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partialclass _Default : System.Web.UI.Page {protected void Page_Load(object sender, EventArgs e) { } [System.Web.Services.WebMethod]public static string Test() {return"Success"; }} 

There is a bug in the beta build that prevents codebehind page methods from working, just incase requiring static methods weren't already going to make them useless enough..Wink... you have to include them in the aspx file if you want to use them...

See this post for more detailhttp://forums.asp.net/thread/1435443.aspx


hello.

jkolbo is right ony about one thing: there's a bug in the beta build and you can't put them in the code beahind file.

regarding the second part, i will not repeat myself and try to explain (once more) why the old instance page methods sucks...this time, i'll just say why the new static methods are good for. in previous releases, if you didn't want to use page methods due to the performance penalties associated with them, you'd have to use web services. static page methods lets you get the some thing without having to develop webservices


Hi,

Just because someone doesn't want to develop webservices is not a compelling reason to take away the functionalities of the old PageMethods. Performance was still better than a complete postback(which is what most of the internet is using). There should atleast be an alternative. Now we got 2 very similiar methods that do the same thing as oppose to 2 distinct methods that do different things.


Hello.

mnn888:

Performance was still better than a complete postback(which is what most of the internet is using). There should atleast be an alternative. Now we got 2 very similiar methods that do the same thing as oppose to 2 distinct methods that do different things.

this is the kind of thing to which i completely disagree! page methods had to send everything back to the server (ie, all the form's firlds, including hidden ones) and they only returned a value from the server. you don't need a postback to do this! if you need to send some values back to the server why not use javascript + web service method call or static page method call? they're a lot better that instance page methods!

if page methods updated the viwestate+control state, i'd be quite and i would be the 1st to say: bring them back. however, that didn't happened...so i'm not sure on where's the performance gain in using old page methods...can you see it?


One other thing to add. AutoEventWireup for the Page must be set to "true" or else the JS proxy is never generated.


hello.

as you can see by my previous sample, there's no need to have autoeventwireup set to true for gettig the proxy inserted on the client side. why?do?you?say?that?

Luis Abreu:

hello.

how about using an updatepanel or a web method? you do say that you need to refresh the UI...btw, i do think that you can access session state from a static method:

<%@. 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">
[System.Web.Services.WebMethod]
public static int O()
{
HttpContext ctx = HttpContext.Current;
ctx.Session["i"] = Convert.ToInt32(ctx.Session["i"]) + 1;
return Convert.ToInt32( ctx.Session["i"] );
}

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);

if (!this.IsPostBack)
{
HttpContext ctx = HttpContext.Current;
ctx.Session["i"] = 0;
}
}
</script
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="manager" />
<div>
<input type="button" runat="server" id="bt" onclick="handleClick()" />
</div>
</form>
<script type="text/javascript">
function handleClick()
{
PageMethods.O(function(res){ alert( res ); });
}

</script>
</body>
</html>

that sample simple returns an int. maybe you can adapt it so that it returns what you need.

I'm a relative novice to ASP.Net AJAX, so please forgive me if i'm doing something blaringly obviously wrong here, but i copied and pasted the code shown above exactly, and when i press the button on the form, instead of the number "0" being displayed in the alert box, it is in actual fact displaying the entire html source of the page.

Any idea why this is happening?