Showing posts with label pagemethods. Show all posts
Showing posts with label pagemethods. Show all posts

Wednesday, March 28, 2012

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,

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?

PageMethods

Hi,

I ama developing web application using ASP.NET, and I use atlas framework in my app. I have a problem with using PageMethods, I want to return value which came from page to another javascript but I can not,

Normal Page Method usage

function sayHelloFromPage() {

PageMethods.HelloWorld('Mehmet',onComplete);

}

function onComplete(result) {

}

what I wantto make it

functioncallSayHelloFromPage() {

var Result = sayHelloFromPage();

}

function sayHelloFromPage() {

PageMethods.HelloWorld('Mehmet',onComplete);

}

function onComplete(result) {

return result;

}

Hi

PageMethods.HelloWorld('Mehmet',onComplete);

The above call happens asynchronously, which means the call is send to the server and the client does not wait for the call to complete; therefore, you don't see the results immediately instead you have to get the results in the onComplete event, which is fired when the call completes.

Whatever you want to do with the results, e.g. change an HTML element, you have to do it in the onComplete function.

PageMethod vs WebSerivce/ServiceMethod

I've seen people say that we shouldn't use PageMethods and should stick with using web services as is currently written, however, I've not seen a reason why. My situation right now is that I want to combine the HoverMenuExtender and DynamicPopulateExtender to display a preview of an item for my gridview. However, my site uses forms authentication, and if I try to pull the html (screen grab) from the page, I just get the forms login page. So I'm curious as to why I shouldn't use a page method which wouldn't have the authentication problem. We already have a webservice running, and I'd rather use that webservice, but since it seems like I can't - I'd rather use a page method then start another webservice.Surely someone has an opinionWink
Surely someone has an opinionWink
Performance would come to mind. A page method requires an (almost) complete run through the page life cycle. Only the render phase is scipt.
Hi,

a page method doesn't require a full run through the page lifecycle. For this reason it is the preferred alternative to a partial postback, where the page goes through all its lifecycle.

Also, in a partial postback, even if only the html for the controls to update is sent in the response, all the web controls are actually rendering their content (but they do it writing into a NullTextWriter).
PageMethod:
I and the IL code disagree. The ScriptModule Registers the PageServiceHandler which in turn sets a RenderMethodDelegate. Therefor, the page runs up unitl the Render method like it would normally. -> Less performance than a WebService call.

Thanks for the heads up on the UpdatePanel. Checked out the IL Code and there it is (the RenderMethodDelegate) in hte ScriptManager.
Hi,

apologies for the confusion I made in my last post, you're perfectly right.

However, my opinion is that the choice between a page method and a web service should be driven by the particular scenario (the data to expose, the need for the elaboration to access the controls on the page) and not by performance.

PageMethods is not defined - Modal Popup

Just upgraded from RC1 to the RTM copy of AJAX and found everything is working for me (with the normal changes to the AutoCompleteExtender) except for my modal popups.

When I attempt to use the client side java script, I get a javascript error:

"PageMethods is not defined."

Here is my JavaScript code:

function myModalPop(regID){ $get("hidRegID").value = regID; PageMethods.popModal(regID, Add_Complete, Add_Timeout, Add_Error);}

and the code behind is:

[System.Web.Services.WebMethod]public static string[] popModal(string regID) { gcmControl DSsend =new gcmControl(); DataSet dsMet =new DataSet(); dsMet = DSsend.gcmDS(dsMet,"SQL","dbAll","SELECT * FROM dbo.tblFinRegister WHERE regID = '" + regID +"' AND clubID = '" + clubID +"'","tblFinRegister"); DataTable tblFinRegister = dsMet.Tables["tblFinRegister"]; DateTime dtRegDate = Convert.ToDateTime(tblFinRegister.Rows[0]["regDate"]);string regDate = dtRegDate.ToString("d");string payeeID = lookupPayee(Convert.ToInt32(tblFinRegister.Rows[0]["payeeID"]));string chartID = tblFinRegister.Rows[0]["chartID"].ToString();string regNumber = tblFinRegister.Rows[0]["regNumber"].ToString();string regPayment;if (tblFinRegister.Rows[0]["regPayment"].ToString() =="0.00") { regPayment =""; }else { regPayment = tblFinRegister.Rows[0]["regPayment"].ToString(); }string regDeposit;if (tblFinRegister.Rows[0]["regDeposit"].ToString() =="0.00") { regDeposit =""; }else { regDeposit = tblFinRegister.Rows[0]["regDeposit"].ToString(); }string regRecon = tblFinRegister.Rows[0]["regRecon"].ToString();string regMemo = tblFinRegister.Rows[0]["regMemo"].ToString();return new string[] { regDate, payeeID, chartID, regNumber, regPayment, regDeposit, regRecon, regMemo }; }
Any suggestions would be fantastic.The way the Toolkit calls page methods is such that no changes are necessary from ASP.NET AJAX RC to 1.0. However, if you're using the ASP.NET AJAX PageMethods wrappers, they made a breaking change such that you now need to set EnablePageMethods=true on your ScriptManager in order to call PageMethods like it seems you're doing above.

PageMethods in UserControl

Sorry if this has been asked before, but the search on the forum does not appear to be working. Everything returns "no results" even a search on "atlas"Smile [:)].

Anyway, is it possible to have web methods in a usercontrol and call them from javacript. I have successfully implemented the PageMethods.SomeMethod from a page but not from a User Control.

Anyone know how to do this?

Thanks,

Joe

No, PageMethods on user controls are not supported.


Will PageMethods be supported the future. I was planning on using PageMethods in controls, to me this would make sense to have.

Thanks.

hello.

i'm tented to say that it won't happen...though i might be wrong...


If there is some callback functionality that you need to use on different pages throughout your site, the best way forward would be to use the asmx web service model. This is much easier than it sounds, and the tutorial is great.

This model is more efficient than PageMethods, where ASP.NET has to initialise a Page instance from viewstate/http to get access to the method you need.

It seems to me that UpdatePanel and PageMethods have been included primarily because of ease of integration into existing sites. If you have the time to optimise, however, then the web service model is the way to go...

Cheers,
Carlos
Hi, thanks for the informaiton. can you send me an example how to use webservice model with user controls..

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 CallBack Wont Fire

What conditions will cause the callback function to not fire when using the PageMethods class?

First my javascript:

<scripttype="text/javascript"language="JavaScript">

function FindTheResult()

{

var txt = document.getElementById("ctl00_contentPlaceHolder_txtBib").value;

PageMethods.FindResultMethod(txt, FindResultDone);

window.status = txt;

returnfalse;

}

function FindResultDone(arg)

{

window.alert(arg);

}

</script>

and then my codebehind:

[WebMethod]

public string FindResultMethod(string bib)

{

return "Hello";

}

FindResults() is firing because my status bar gets updated. But the FindResultDone function is not firing.

A client script error in javascript may have happened in this line:

PageMethods.FindResultMethod(txt, FindResultDone);

In this line, FindResultDone() is expecting a parameter but was not supplied


Ok, that makes FindResultDone actually fire. But how do utilize the return string from my WebMethod:public string FindResultMethod(string bib) ?

Leaving out the ( ) and any paramaters usually just passes the return string back to the callback method. See this atlas.asp.nettutorial code. The callback has no parameters, yet the function does.

This all worked flawlessly with the October release.

AlvinVi wrote:

A client script error in javascript may have happened in this line:

PageMethods.FindResultMethod(txt, FindResultDone);

In this line, FindResultDone() is expecting a parameter but was not supplied


Hi,

mxmissile wrote:


PageMethods.FindResultMethod(txt, FindResultDone);

This statement is correct, you don't need to add the () or any parameters because you have to pass a reference to the method (callback) that will be called when the server method returns.

I've tried your code (that seemed correct to me) on a machine and in fact everything went ok: the callback is fired and the string is displayed.

But then I've tried it on another machine and I got the strange behavior that you reported: the callback isn't fired because the asynchronous request returns a response with status code 500 (Internal Server Error). You could try to make the following call:

PageMethods.FindResultMethod(txt, FindResultDone, FindResultTimeout, FindResultError);

and then add these two functions:

function FindResultTimeout() {
alert('timeout');
}
function FindResultError(result, response) {
alert(response.get_statusCode());
}

Try to run the code and see what happens: probably the FindResultError callback will be fired.

Now, I suppose that you have added an <atlas:ScriptManager> tag in your page. Try to add a reference to a web service (for example, create a simple WebService.asmx)

<atlas:ScriptManager id="scriptManager" runat="server">
<Services>
<atlas:ServiceReference Path="WebService.asmx" />
</Services>
</atlas:ScriptManager>

and the run the code: which callback is fired now? In my case, the FindResultDone callback is fired and the response error disappeared...

I think it's a strange behavior.. I'll try to understand what is happening, but has anyone got ideas on what is going on?

Ok, ill try adding the webmethod to a seperate asmx file to see what happens.

I also have some other data:

function FindResultError(result, response) {
alert(response.get_statusCode());
}

When I do this, the alert window just says "null", so the error function is being called at least I think.

My page is using a Master Page, when I move the code to a "un-master page"ed" aspx file it works great.

I started a new test atlas project and everything is working great, until I start using Master Pages. It fails if I put the <atlas:ScriptManager tag is in the <head> of the Master Page or in the content section.

Anyway thanx for the input, still hacking at it...


Hi,

mxmissile wrote:


My page is using a Master Page, when I move the code to a "un-master page"ed" aspx file it works great.


You mean the first code you posted? I've tried it without a master page and it's working on a machine, but failing on another.

mxmissile wrote:


Ok, ill try adding the webmethod to a seperate asmx file to see what happens.


Just create a new web service (WebService.asmx), reference it in the<atlas:ScriptManager> tag but continue to call the method definedin your page (PageMethods.FindResultMethod). In my case this solved theproblem but it's a strange behavior.

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.

PageMethods and xml-script?

So, I've only seen a couple posts that touch on this, and none had a direct answer. What I'm looking to do is to call one of my pages' WebMethods using the declarative syntax. I'm not sure exactly how to do that.

Using javascript it works fine, so I know that I have the rest of the thing set up right, but for whatever reason using all the components and bindings and all that just.

Conversely, I tried doing it with just a regular web service and binding,a nd that works fine too. Anyone successfully use declarative markup with WebMethods that are served from the aspx page?

hello.

currently, you can only do that if you call web service methods, you can, however, develop your own class which could be used from xml-script (you can adapt the ServiceMethodRequest to do that).


I'm not sure, I guess, what differentiates a webmethod called from the codefile from a webmethod called from a web service, in the eyes of xml-script. What is the body of code that influences the xml-script schema? I assume it's one of the classes in atlas.js, but I'm not sure which one. I'm interested in hearing how you'd do it if it were your task, though.

thanks,

Paul


hello.

take a look at the servicemethodrequest class. you just have to build a similar class but instead of using the servicemethod class internally, you should use teh pagemethod class.


Oh, I see. yeah, I spent the last half hour or so just reading (again) the atlas.js source. I'm not as sharp in javascript as I am in server-side stuff, but I'm starting to get the flow. thanks for the tip, if I end up implementing this I'll post the results.

Wow, ok, that was a LOT easier than I thought it would be. Thanks for the tip. Code follows. I went ahead and put it in my namespace b/c I didn't want to pollute teh Sys.Net namespace, but feel free to take, modify, whatever at liberty. As you suggested, the main thing to do here was to take the existing ServiceMethodRequest class and swap out the ServiceMethod references for PageMethod ones. I also pulled otu some of the member variables that I knew I wouldn't need (e.g. url-related ones) to tidy it up. This is a first draft, so I might find more that I want to do now that I have my teeth in it.

Thanks again!!

Paul

/*

Title: PageMethodExtender.js

Author: Paul Vencill

Summary: Add-on class to Atlas that will allow web methods exposed in the page's codefile to be called from the page's xml-script.

*/

Type.registerNamespace(

'Com');

Type.registerNamespace(

'Com.VelocityDataSolutions');

Com.VelocityDataSolutions.PageMethodRequest =

function() {

Com.VelocityDataSolutions.PageMethodRequest.initializeBase(

this);var _methodName =null;var _parameters =null;var _response =null;var _userContext =null;var _result =null;var _request =null;var _timeoutInterval = 0;var _priority = Sys.Net.WebRequestPriority.Normal;this.get_url =function() {return _url;

}

this.set_url =function(value) {

_url = value;

}

this.get_appUrl =function() {return _appUrl;

}

this.set_appUrl =function(value) {

_appUrl = value;

}

this.get_methodName =function() {return _methodName;

}

this.set_methodName =function(value) {

_methodName = value;

}

this.get_parameters =function() {if (_parameters ==null) {

_parameters = { };

}

return _parameters;

}

this.get_response =function() {return _response;

}

this.get_result =function() {return _result;

}

this.get_timeoutInterval =function() {return _timeoutInterval;

}

this.set_timeoutInterval =function(value) {

_timeoutInterval = value;

}

this.get_priority =function() {return _priority;

}

this.set_priority =function(value) {

_priority = value;

}

this.completed =this.createEvent();this.timeout =this.createEvent();this.error =this.createEvent();this.aborted =this.createEvent();this.invoke =function(userContext) {if (_request !=null) {returnfalse;

}

var _pageMethod =new Sys.Net.PageMethod(_methodName);

_request = _pageMethod.invoke(_parameters, onMethodComplete, onMethodTimeout,

onMethodError, onMethodAborted,

this ,

_timeoutInterval, _priority);

function onMethodComplete(result, response, target ) {

_request =

null;

_userContext = userContext;

_response = response;

_result = result;

target.completed.invoke(target, Sys.EventArgs.Empty);

}

function onMethodError(result, response, target ) {

_request =

null;

_userContext = userContext;

_response = response;

_result = result;

target.error.invoke(target, Sys.EventArgs.Empty);

}

function onMethodTimeout(request, target ) {

_request =

null;

_userContext = userContext;

target.timeout.invoke(request, Sys.EventArgs.Empty);

}

function onMethodAborted(request, target ) {

_request =

null;

_userContext = userContext;

target.aborted.invoke(request, Sys.EventArgs.Empty);

}

returntrue;

}

this.abort =function() {if (_request) {

_request.abort();

}

}

this.getDescriptor =function() {var td = Com.VelocityDataSolutions.PageMethodRequest.callBaseMethod(this,'getDescriptor');

td.addProperty(

'methodName', String);

td.addProperty(

'parameters', Object,true);

td.addProperty(

'response', Sys.Net.WebRequestExecutor,true);

td.addProperty(

'result', Object,true);

td.addProperty(

'timeoutInterval', Number);

td.addProperty(

'priority', Number);

td.addMethod(

'invoke');

td.addMethod(

'abort');

td.addEvent(

'completed',true);

td.addEvent(

'timeout',true);

td.addEvent(

'error',true);

td.addEvent(

'aborted',true);return td;

}

Com.VelocityDataSolutions.PageMethodRequest.registerBaseMethod(

this,'getDescriptor');

}

Com.VelocityDataSolutions.PageMethodRequest.registerClass(

' Com.VelocityDataSolutions.PageMethodRequest', Sys.Component);

Sys.TypeDescriptor.addType(

'script','pageMethod', Com.VelocityDataSolutions.PageMethodRequest);

cool!

that's the spirit :)


Hi,

thanks for posting the code, Paul.

Glad to, I'm very excited about this. I also went ahead and built a Page subclass that inserts a ScriptManager control if there isn't one and pulls in the xml-script from an external file (by default located in the same folder and with the same name as the parent document but with a .ascr extension.). Here's teh code for that subclass as well. It works, but I'm still polishing it to make it a little more robust, add comments, etc etc. I just wanted to see if i could hack my way through it.

using

System;

using

System.Web.UI;

//using System.Xml;

using

System.Xml.XPath;

///

<summary>

///

Summary description for AtlasPage

///

</summary>

public

classAtlasPage : System.Web.UI.Page

{

privatestring _xmlScript;privatebool _hasScriptManager;protectedoverridevoid OnInit(EventArgs e)

{

addScriptManager();

addAtlasScript();

base.OnInit(e);

}

protectedstring _scriptFile;publicstring ScriptFile

{

get {return _scriptFile; }set { _scriptFile =value; }

}

privatevoid getXmlScript()

{

if(String.IsNullOrEmpty(_scriptFile))

{

string url = Request.Url.ToString();

url = url.Replace(

".aspx",".ascr");

_scriptFile = url;

}

try

{

XPathDocument xdoc =newXPathDocument(_scriptFile);XPathNavigator xNav = xdoc.CreateNavigator();

xNav.Select(

"script");

_xmlScript =

String.Format("\n{0}\n",xNav.OuterXml.ToString());

}

catch

{

_xmlScript =

String.Format(@."<!-- File not found: {0} -->","xml-script");

}

}

privatevoid addAtlasScript()

{

getXmlScript();

LiteralControl lit =newLiteralControl(_xmlScript);this.Controls.AddAt(this.Controls.Count - 1, lit);

}

privatevoid addScriptManager()

{

_hasScriptManager =

false;

iterateCollection(Controls);

if (!_hasScriptManager)

{

Microsoft.Web.UI.

ScriptManager scm =new Microsoft.Web.UI.ScriptManager();this.Header.Controls.Add(scm);

}

}

privatevoid iterateCollection(ControlCollection ctrls)

{

foreach (Control ctrlin ctrls)

{

if (ctrl.HasControls())

{

iterateCollection(ctrl.Controls);

}

if (ctrl.ToString().Contains("ScriptManager"))

{ _hasScriptManager =

true; }

}

}

}

Paul Vencill

Velocity Data Solutions. LLC

www.velocitydatasolutions.com

PageMethods and Objects

Is it possible to send objects as parameters for a PageMethod and to return objects as the result of a PageMethod? I have a large amount of data (and multiple data types) that I want to collect from a form then send it to the server, and it would simplify things greatly if I could create an object rather than sending a bunch of individual parameters.

Thanks

Patrick

Yes, you can.

Among the list of of useless responses that one is very close to the top. Now I'll admit I didn't ask how to use objects in page methods if it's possible, but I tend to think the how is implied by the fact that I took the time to ask the question in the first place. Sense I appear to be wrong in my assumptions here is the followup question...

How do you use objects as a parameter or return value when calling a PageMethod? As far as I can see if I have a class defined in my website (call it MyClass) there is no equivilant class available in the client script.

Patrick


Sorry for the short response. First take a look athttp://ajax.asp.net/docs/tutorials/ConsumingWebServicesWithAJAXTutorial.aspx (especially the last example on the page) and see if that answers your questions.

If you retrieve something from the web service (or page method), modify it on the client, and then send it back, you shouldn't have to do much. (The serialization should do all the work for you.) But it sounds like you might need to instantiate an object of this complex type on the clientfirst. In that case, notice the [GenerateScriptType(typeof(ColorObject))] attribute on the web service. That's the indicator to ASP.NET AJAX that the proxy it generates should include a definition of that type.


The short answer is that you can, and all you have to do is write your pagemethod signature as you would for a server-side call but w/ the webmethodattrbiute added. The framework reflects on those WebMethods and makes proxy classes in javascript to represent all the objects in the parameters and return types for you. Pretty cool feature, if you ask me. THe only downside (sorta) is that it chokes on certain complex objects (e.g. objects nested in objects), so you might have to write your own custom converter, per the link the other guy sent you.


Thanks for the link. I've taken a look and the samples look like they will work for me.

Monday, March 26, 2012

PageMethods is undefined when calling webservice from usercontrol

I have the following code to call a webservice in an aspx file. But the same code does not work in a usercontrol that I have created. I always get the message that 'PageMethods is undefined'. On the aspx page it generates the following:

<script type="text/javascript">
<!--
var PageMethods = { HelloWorld:function(s,onMethodComplete, onMethodTimeout, onMethodError) {return Web.Net.PageMethodRequest.callMethod("HelloWorld",{s:s}, onMethodComplete, onMethodTimeout, onMethodError); }
}
// -->
</script>

but in the usercontrol this variable is not generated. The following is the code in the aspx page which is very similar to the code in the user control. Please help!

<atlas:ScriptID="Script1"runat="server"Path="~/ScriptLibrary/AtlasCompat.js"Browser="Mozilla"/>

<atlas:ScriptID="Script2"runat="server"Path="~/ScriptLibrary/AtlasCompat.js"Browser="Firefox"/>

<atlas:ScriptID="Script3"runat="server"Path="~/ScriptLibrary/Atlas.js"/>

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

[WebMethod]

publicstring HelloWorld(string s)

{

return"Hello '" + s +"'";

}

</script>

</head>

<body>

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

Enter your name:

<asp:TextBoxid="nameTextBox"runat="server"></asp:TextBox>

<buttonid="buttonGo"onclick="return OnbuttonGo_click()">GO</button>

</form>

<scripttype="text/javascript"language="JavaScript">

function OnbuttonGo_click()

{

//textbox string value passed as a param to the server method

PageMethods.HelloWorld(document.getElementById("nameTextBox").value, OnWebRequestComplete1);

returnfalse;

}

PageMethods are currently not supported inside user controls. I've open a bug to track that issue. Thanks.


If I put the WebMethod in the calling page I can call it from the usercontrol, which allows for the functionality that I desire. This is not as clean as I hoped for but it will work.

Thanks


Has this been fixed in the December release? It appears not, unless I am doing something incorrect. I am getting the js error 'Web' is undefined. Even my work around for this problem apears to be broken.

PageMethods is undefined - Beta1

I tried everything but couldn't get rid of the "PageMethods is Undefined". Also I couldn't get the webservice to work from the javascript. Please can someone have a look at this code and point out the error? I tried putting 'static' in front of SomeMethod(), but it still doesnt work. I was wondering if there may be any deployment issue!

default.aspx.cs file

public

partialclassDefault : System.Web.UI.Page

{

protectedvoid Page_Load(object sender,EventArgs e)

{

}

[

WebMethod]public string SomeMethod(string name)

{

return name;

}

}

default.aspx

<formid="Form2"runat="server"><asp:ScriptManagerrunat="server"ID="scriptManager"></asp:ScriptManager>

<div>

Search for

<inputid="SearchKey"type="text"/><inputid="SearchButton"type="button"value="Search"onclick="DoSearch()"/></div><scripttype="text/javascript"language="javascript">function DoSearch()

{

PageMethods.SomeMethod(

"HiThere", OnRequestComplete);}function OnRequestComplete(result)

{

alert(result);

}

</script></form>

Thanks

Richmond

I got the answer from the following discussion. It works!

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

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?

PageMethods is Undefined

HI,

its Urgent

I am Getting Same Error Could u please Help me Out..

Here is My Code..

using System.Web.UI.HtmlControls;

using System.Web.Services;

using Microsoft.Web.Script.Services;

using Microsoft.Web.Script;

[WebMethod]publicvoid GetNewMessage()

{

string str ="Hello";

Response.Write(str);

}

Javascript

PageMethods.GetNewMessage();

<asp:ScriptManagerID="ScriptManager1"runat="server"EnablePartialRendering="true">

<Scripts>

<asp:ScriptReferencepath="scripts.js"/>

</Scripts>

</asp:ScriptManager>

Thanks in Advance,

Suman...

Please its Urgent...

this is not sufficient to debug your error ... you need to show us the whole thing ... and what kind of error is that? JavaScript or server error?


check this post out ... same error as yours:http://forums.asp.net/t/993893.aspx


ScriptManager has to have EnablePageMethods=true and the WebMethod has to be static.


hi here is my full code..

aspx file

<bodystyle="margin: 0px;padding: 0px;">

<formrunat="server"action="RF_Message.aspx">

<divid="ContentPanel">

<divid="MessageList">

<asp:ScriptManagerID="ScriptManager1"runat="server"EnablePartialRendering="true"EnablePageMethods="true"EnableScriptGlobalization="true"EnableScriptLocalization="true">

<%--<Scripts>

<asp:ScriptReference Path="scripts.js" />

</Scripts>--%>

</asp:ScriptManager>

</div>

</div>

</form>

</body>

</html>

<scriptlanguage="javascript"type="text/javascript">

var str = PageMethods.GetNewMessage();

alert(str);

var result = document.createElement("div");var divlist = el("MessageList");

result.innerHTML = str;

divlist.appendChild(result);

function el(id)

{

return document.getElementById(id);

}

</script>

aspx.cs file..

using System;

using System.Data;

using System.Configuration;

using System.Collections;

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;

using System.Web.Services;

using System.Web.Script.Services;

using System.Web.Script;

publicpartialclassRF_Message : System.Web.UI.Page

{

//ChatManger Chatmanger = ChatManger.GetChatManager();

protectedvoid Page_Load(object sender,EventArgs e)

{

}

}

#region Script callback function

[System.Web.Services.WebMethod]

publicstaticstring GetNewMessage()

{

string str ="Hello";

return str;

}

#endregion

}

I am Getting Javascript Error While Running...

i am Getting alert Undefined...


RIght, you're executing that embedded script block as the page gets to it; pagemethods haven't been created yet (that happens during the clientside init, iirc. Try pulling all that code into your pageLoad() javascript function and see if that doens't help.