Why do ASP.NET AJAX page methods have to be static?
AJAX, ASP.NET, OO By Dave Ward. Updated June 13, 2008
Dozens of variations on the title of this post are some of the most common searches that bring people here to Encosia. Unfortunately, the search engines all point to a post that doesn’t answer the question. It’s also a frequent question raised on the ASP.NET message boards, typically without a satisfactory answer provided.
However, it is an important question, the answer to which is important to understand. So, in an attempt to fill in this gap for the searchers and perhaps preemptively help others, I want to proceed to answer it as thoroughly as possible without overly complicating the whole business.
In order to do this, we’ll have to take a brief tour of WebForms, including:
- Understanding what the Page class is, and why we have it.
- One specific thing that the Page class does for us.
- How this is accomplished, behind the scenes.
- What the static keyword entails, when used with a method.
- Finally, why page methods must be static.
Note: Please bear in mind that I have taken great liberties in simplifying these concepts down to only what is necessary to answer the central question. What I will show you is conceptually accurate, but some of the implementation details are much more complex than what you will see here.
Understanding what the Page class is, and why we have it
Contorting the stateless HTTP protocol to accommodate ASP.NET’s WebForm paradigm was a considerable task for the ASP.NET team to accomplish. On top of that, going from the inline execution model of ASP classic to the event-driven model of ASP.NET also required major changes.
As such, the ubiquitous WebForms Page class was created to solve these various problems. Take this snippet, for example:
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Hello World. } }
I’m sure you’re familiar with the Page_Load event. The very first ASP.NET code example you were exposed to probably involved the Page_Load event. How about this portion of it though?
public partial class _Default : System.Web.UI.Page
To get you started quickly, those examples may not have explained that part very well (if at all). Later, after you get up and running, it can be easy to simply gloss over this line as cruft that comes with writing an ASP.NET page.
What this declaration means is that your code extends the Page class. Because of this, your code will include the functionality of the entire ASP.NET Page class, instead of standing on its own and requiring you to implement the mundane details.
If you’re more familiar with something like ASP classic or PHP, you can think of this Page inheritance as being functionally similar to a powerful include file that you use site-wide.
One of the Page’s most powerful features: Persistence
The Page brings a lot to the table. However, to answer the question of why page methods must be static, we need to focus on persistence.
Consider this example:
<asp:Label runat="server" id="Label1" /> <asp:Button runat="server" id="Button1" OnClick="Button1_Click" />
protected void Button1_Click(object sender, EventArgs e) { Label1.Text += DateTime.Now.ToString(); }
Each time the button is clicked, the label will have the current time and date appended to its current contents. Even this elementary example illustrates how the WebForms Page automatically provides persistence for us.
We take for granted that the Page will provide us this Label1 object after an HTTP POST from the browser. We also assume that it will automatically have a Text property with that Label’s current value.
However, this data would not normally be included in the POST data sent to the server. Only form elements are sent from the browser. The Label renders as a span element, which means that its state is not POSTed by the browser.
So, how does the Page provide us with this data anyway? Persistence.
Understanding how the Page does this
To implement this encompassing layer of persistence, the ViewState was created.
Each time a page is rendered to the browser, the Page serializes the state of its controls and then includes that information in the returned HTML, via a hidden form field named __ViewState. When a postback occurs, this hidden field can then be de-serialized to create an instance of the Page in the same state that it was at the end of the last request.
Oversimplifying, you can envision this constructor being used to re-instantiate the Page, at the beginning of every postback:
Page _Default = new Page(Request["__ViewState"]);
In our example above, the Page created through that process would look something like this after one postback:

This re-instantiation of the Page from the ViewState is what keeps the entire WebForms machine rolling, postback after postback.
What does it mean that a method is static?
A static method is simply one that is disassociated from any instance of its containing class. The more common alternative is an instance method, which is a method whose result is dependent on the state of a particular instance of the class it belongs to.
For example, both of these statements would return precisely the same string, but accomplish it through different types of methods:
// ToString() is an instance method of the DateTime class. // Its result depends on the value of each DateTime instance. return DateTime.Now.ToString(); // String.Format is a static method of the String class. // Its result is not related to any instance of the String. return String.Format("{0}", DateTime.Now);
The key difference to understand is that a static method can be called without setting up a proper instance of the class it belongs to.
In a sense, it is a stateless method.
So, why do page method calls have to be static?
If you’re implementing page methods, you’re probably well aware of their excellent performance. They are especially performant compared to the UpdatePanel’s partial postbacks.
They are efficient largely because they do not require the ViewState to be POSTed and they do not create an instance of the Page, while partial postbacks do both of these things. As we now know, a page method couldn’t create an instance of the page even if desired, since the ViewState isn’t provided in the request.
This is exactly why they must be marked as static. They cannot interact with the instance properties and methods of your Page class, because a page method call creates no instance of the Page or any of its controls.
Page methods are roughly equivalent to shorthand for standalone web services. In fact, the ScriptManager even calls them exactly as it would a regular web service.
Conclusion
While forcing the page method to be static is primarily due to technical reasons, I would suggest that it’s actually a good thing. If page methods transmitted the ViewState along with their request, in order to instantiate the Page, they would immediately lose a majority of their benefit.
Forcing the method to be static is necessary to confer most of the benefits of using page methods. Sure, it would be nice to be able to access control properties directly from within page methods, but not at the expense of transmitting volumes of extraneous data about every other control on the page.
Instead of fighting against this limitation, I say embrace efficiency.
Similar posts
What do you think?
I appreciate all of your comments, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums or Stack Overflow instead.
If you're replying to another comment, use the threading feature by clicking "Reply to this comment" before submitting your own.
12 Mentions Elsewhere
- Dew Drop - April 16, 2008 | Alvin Ashcraft's Morning Dew
- rascunho » Blog Archive » links for 2008-04-16
- Interesting Finds: 2008.04.17 - gOODiDEA.NET
- Reflective Perspective - Chris Alcock » The Morning Brew #75
- Wöchentlichen Rundablage: ASP.NET MVC, Silverlight 2, WPF, WCF… | Code-Inside Blog
- Weekly Links: ASP.NET MVC, Silverlight 2, WPF, WCF… | Code-Inside Blog International
- April 28th Links: ASP.NET, ASP.NET AJAX, ASP.NET MVC, Silverlight - ScottGu's Blog
- 4月28日链接篇: ASP.NET, ASP.NET AJAX, ASP.NET MVC, Silverlight - Joycode@Ab110.com
- Eye On .NET - Hisham Elbreky
- Why Asp.net ajax page methods have to be static - Yizhe Online Tablet
- Why do ASP.NET AJAX page methods have to be static? « Talibkhan’s Weblog
- Nitin's Blog » Asynchronously posting client side variables to server using jquery and web method



Your blog is priceless! Clearly the best blog about ASP.NET AJAX!
What’s the benefit over using a web service, then? Page/UserControl methods in Anthem.NET keep track of ViewState, so I don’t see why MS Ajax can’t do it.
As far as I know, page methods have no technical benefit over web services. They are very similar.
It does seem that they put up less barrier to entry for developers who aren’t comfortable using web services though. If being able to write the page method in the page’s code-behind gets more people using them, I think that’s a win.
If you need something that keeps track of ViewState, you can always use an UpdatePanel. The Anthem.NET controls have a lot of the same drawbacks the UpdatePanels have anyway (they shuffle the entire ViewState up and down, regardless of how little of it is needed for a particular operation).
There’s no magic AJAX bullet. Either you have to bloat your requests and responses with ViewState, or you have to work within the limitations of stateless requests.
Great article, straightforward.
Keep it up!
Insightful article!. thanks.
Great article. I really enjoy the topics you choose to discuss.
One very distinct disadvantage of using PageMethods is a little-discussed phenomenon:
When debugging an ASP.NET page with PageMethods, Visual Studio will cache the result of the PageMethod. So you have to do a clean/rebuild of the solution every time you make any code changes to the PageMethod.
Interesting, I didn’t know that. Good information. Thanks for the comment.
Great article Dave! I had actually did some research on this subject myself about 2 weeks ago, never arriving at a definitive answer.
The only thing that is missing in this page methods approach is the javascript ajax-enabled UI library that you can use with page methods. You get JSON data back, yes. But you have to present it, and here we need a library to do that (including validation and error handling). I personally can’t afford to write javascript ajax-enabled UI. For example, if you use a library such as ExtJS, there is no such thing as page methods, let along asp.net ajax :)
Having said that, I honestly don’t see how these page methods can be useful if there is no UI library (all you can do is to write your own code in javascript to build UI elements, which is quite a challenge to say the least :)
In the not too distant future, I’ll probably write a post on generating the UI client side.
If you make good use of CSS for layout/styling, building the semantic structure on the fly turns out to be relatively easy.
For example, that’s how I build the table on this site. I was using an UpdatePanel to update a user control with the same content. Moving to the web service call gave me an order of magnitude performance gain (which was more than I had even expected).
Great summary. One similar question I have always had is: what are the differences between a page method and a callback method? I assume its similar to the situation in this article, but I’ve never actually found a good answer.
More or less, you can think of the callback methods as ASP.NET 2.0′s precursor to page methods. They are also still great for developing AJAX server controls, as web services and page methods aren’t very feasible for that.
Thanks Dave
really great article.
thanks again
I just discovered your blog from Scott Gu’s blog post. This was a great post, thank you. I’ve got a question about static page methods. How can you retrieve the current user’s identity from inside one? For example, let’s imagine you had a method to update someone’s phone number (they enter it in a textbox and you have a button that is just calling a javascript function, please excuse my horrible syntax)
Page.MyStaticMethod(string username, string newPhoneNumber)
I would be worried about someone just calling the javascript method manually with someone else’s username. Is there anything to prevent someone from manipulating script and changing the parameters to a page method call? If not, is there a way to just retrieve the username inside the C#? I don’t think you can access User.Identity.Name from inside the C# but I could be wrong…
I could be way off here and missing something simple… sorry if this is confusing.
You are correct that you should avoid using a method that facilitates forging on the client side. In your situation, since a page method call includes the user’s cookies in the request, identity information is available via HttpContext.Current.
For example, to get the username of a logged in user, use HttpContext.Current.User.Identity.Name in your page method.
“As we now know, a page method couldn’t create an instance of the page even if desired, since the ViewState isn’t provided in the request.
This is exactly why they must be marked as static.”
That doesn’t make any sense and is not the reason. The real question is why don’t you allow us to create non-static methods that DO post back the viewstate, so that we can access the page instance?
As I see it, we have absolutely no use for static page methods. We can already use webservices for that.
As I recall, in the early betas we did have page methods that were non static.
As far as I know, those heavyweight page methods from beta were canned due to terrible performance. If you’re willing to heft around the ViewState, you might as well just use an UpdatePanel. Passing the ViewState on a page method call defeats the entire purpose.
I’m not sure why, but I’ve found that a lot of people will write a page method, where they won’t write a web service method. I’m not sure what the friction is when it comes to writing web services, but it’s definitely there.
So, if having static page method available makes people more likely to use them, I think that’s a win for everyone.
Dave,
Your article is simply superb. But i have a question to you, forgive me if i asked anything silly.
If Page Methods don’t pass view state then as per your statement, page instance will not be created. Then how come if a page has enableViewState=”False” creates a new Page Instance when every time a page is posted to server. Please clarify me.
Sam
@author:
You are wrong.
regarding “Each time a page is rendered to the browser, the Page serializes its controls (including their properties)” I can tell you the controls are NOT serialized in the Page Viewstate. Only the controls’ viewstate is put there.
Don’t trust me? Read this : http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx
I think you may have missed the note that I purposely oversimplified the details of the process.
Exactly what’s serialized isn’t relevant to understanding why page methods must be static. Knowing that important state information is transmitted in the ViewState is the key.
That said, I would have to argue that serializing all of a control instances’ properties is serializing the control. Like Dave Reed says in his article:
Very good!
I use a lot this kind of method. But there is a small (or big?) detail: I cannot access the page properties, and this means that I cannot access textboxes, labels, etc (exactly as you said in your post).
So, if you have a very big form, with a lot of fields to save into the database, maybe the best way to do this is using UpdatePanel, because it submits the viewstate and, of course, the control’s values.
Another detail about the Page Methods is about the validation. It is a very useful method to validate complex data. Yeah, single data (email, phone, etc) you can validate using simple java script or the .net validators. But to complex data (if the user already exists, if this or that is true on database) the best way is using Page Method.
Ah, I had some problems when using this feature into user controls (ascx). If you see the generated HTML code, you will see that the call to the Page Method is created based on the Page name, not using the user control. So I think that we cannot use this feature into user controls, just into ASPX pages.
Again: very good post!
Bye.
I would tend to agree that for form submissions, an UpdatePanel is fine (or even a full postback).
Dave — thanks for quoting me, but still not all the properties are actually serialized, only the ones marked ‘dirty’, which typically only includes the ones that were changed dynamically.
Would it be more correct to say that the ViewState is used to serialize any non-default properties of controls that aren’t set declaratively?
I don’t want to get into an argument of semantics, when the end result is all the same in terms of understanding the topic at hand.
More correct, yes. But sometimes even default values are serialized if they are set dynamically :)
I’m not one for arguing over semantics either, but this is a topic [ViewState] that’s already widely misunderstood because it is deceptively more complex than it seems.
Fair enough. I updated that sentence of the post to be more accurate (or less inaccurate):
I certainly defer to you in any matters of the ViewState. I appreciate the feedback, Dave. Thanks!
hi , i am very impressed with ur blog.its realy priceless
Thanks alot for all info on PageMethods and especially on the efficiency of calling PageMethods with static or shared server side methods or functions.
Simple, uncomplicated and to the point, well done!
i have a user control and the ascx.vb file contains a method displaytext(), i have to call it from ascx page using PageMethods.. it’s not working.. it works fine in ASPX page.. do you have any idea??
Page methods don’t work in user controls. Most likely, you should use a web service in that situation.
is this (web service) the only way for the web service??
opps.. “web service??” should be “user control”
————-
is this (web service) the only way for the user control??
Yes, you’d need to use either an ASMX or WCF web service. You cannot define page methods in user controls.
An ASMX web service is almost identical to a page method. If you give that a try, it should come easily.
Thanks Dave
i used web service (ASMX), it’s working fine now!
Good artical Dave.Thanks.
Very good article …Thank you so much…..
Great Information Dave… Thanks Alot.
For Matt April 17th comment on static and debug.
May be this is not the place to tell but still for other’s info on Static I am writing case.
I too faced this problem.
Another problem i faced with static is
We had 2 connection string for french and eng db use to store the conn string on a static string variable depending on the page I use to change the value of variable, due to static variable the value of variable was not changing, (it was not just the case while debugging but during runtime too).
Static: I believe once static variable is used, its memory (value) is the common sharable to all the users who use this variable.
My question is if in a page on clicking a button, a label has to show from ‘A’ text to something 1,2,3… for user1,user2,user3 respectively… if user1 is using the page and get “1″ from static page method, user2 at same time will see “1″ instead of 2.
We may need to test this method with multiple users and behaviour of method simultaneously. If page method has to behave similarly everytime then it is ok. I have a doubt about static pagemethod behaviour for multiple user at same time for different results.
Oh! man.
This is a great great great post.
I read the entire article w/o taking a breath. Nicely done. A great satisfaction after reading your article. I learned from it.
Take care & Thanks.
This is a seriously awesome article. Thanks for taking the time to explain it so clearly.
Interesting article.. Anthem.NET methods don’t have to be static, that must mean that they transmit the viewstate.
Great article; thanks so much for taking the time to put this information together.
Great Article.
Saved me a lot of time..
A solution could be.. calling from the static PageMethods to external webservice project.
in this case you can use non static objects and method on the external ws.
You can also add “ip security” to the external ws.
Let me see if I got it: web methods have to be static because MS decided on a stupid implementation for server-side state serialization, right?
What I mean: of course the meanest and leanest web apps are the ones which do not keep state on the server, whether they are written in Java, ASP.Net, PHP or whatever. But there are apps which cannot be reasonably implemented without keeping state information on the server. However, ASP.Net does not provide a solution for such apps. ViewState provides a workaround, but isn’t really a solution for such apps. Why? Because if your state information is large, serialization and deserialization from ViewState is going to take a lot of time, enough so that your application is slow.
The only solution to developing fast, responsive, really web2 apps using ASP.Net is giving up server controls altogether, use a client-side only Javascript-based Ajax toolkit/framework and work with web services/web methods alone. Which of course have to be session/view state-unaware. But since MS does not provide such a toolkit integrated in ASP.Net, doing so is not quite happy coding. Until you get your toolkit of choice properly interfaced with an ASP.Net backend, it’s not really happy coding.
Web Methods do have an advantage over web services, though: they’re significantly easier and simpler to implement. However, they also have a drawback: if you don’t use them from ASP.Net, it’s not really easy to call them. But then again, JSON-based Web Services implemented using ASP.Net are also not quite straightforward to call from non-ASP.Net code.
IMO, web methods are always the better choice when you implement functionality which is not reusable. You implement web services whenever there’s a chance some other code than the one for which you write your web service will be able to make use of your web service. Whenever you need just a more or less calculation which needs to be performed server-side, but which is pertinent just to the form from which you call that code, a web service is just unnecesarily polluting the global namespace of web services exposed by an application/server/enterprise infrastructure.
Great article Dave!
Hi Dave,
I’m a little worried about the use of Static methods. In a multi-user environment (i.e. just about any web application), I thought that maybe each call to the method would be shared between all users, including any internally declared variables. To test, I created the following:
Called by:
Click here for the test.I open up two browsers, one Chrome, the other Firefox, just to make sure. In the textbox in each browser, I typed the browser name for clarity.
To my pleasant surprise, when I clicked on each “Result” div within the 5 seconds of the first click, the text updated in each respective browser/session was as hoped, namely “Chrome” in Chrome and “Firefox” in Firefox.
I’ve tested this to satisfy myself, but I was wondering if you could elaborate as to how this happens, and why the static WebMethod is not behaving like a static variable. OR, have I made a mistake in my testing, and not proved anything?
Your testing is correct. The reason you aren’t seeing a “shared” behavior across sessions is that each Page instance only exists within the scope of a single HTTP request and then is destroyed.
but static method doesnt depend on instance of the page right na?
Not surprisingly, I dont want anyone other than my own company’s applications calling our web services. Some of our proposed web services will add records to SQL tables. There’s no SS#s or credit card numbers or the like involved, so encryption is not needed. I just dont want someone else calling the web services.
Do static web methods have an advantage from that perspective? Is there existence not exposed to the world like a web service is?
To my knowledge, page methods are as exposed as any ASMX service. However, you can control access to either of them with the standard ASP.NET authorization facilities (e.g. Forms Authentication, Windows Authentication, etc). Using that, you can insure only users that are logged into your application can access the services.
I think our website uses anonymous Windows authentication (I know very little about that end of things…).
However, our website has its own homegrown login/pw mechanism which, when successfully completed, places a customer number into a session variable. Could I not check for the existence of that session variable in my web method and if it isnt there, return a negative response of some sort and not do the SQL table add that the method was designed to do? So while not keeping intruders from calling the web method, it would prevent them from doing any damage.
Sorry if I sound like a dufus, but this Ajax/webservice/webmethod paradigm is all new to me.
That’s right. You’ll have full access to the HttpContext during those AJAX callbacks, including the Session.
You’ll need to reference the Session explicitly though, since there’s no Page instance to shortcut it for you. HttpContext.Current.Session.
Similarly, you can use HttpContext.Current.Response.StatusCode to respond to unauthorized requests with the correct HTTP status code (401 or 403, probably).
Dave,
Excellent, you made my day! I’m going to plunge forward with the web methods then…
A megabyte of thank you’s for your input.
Kerminator
Just an afterthought – that session variable existence approach would not work in a web service, would it?
No problem. Happy to help.
The HttpContext/Session is available in standalone services too. You just need to add EnableSession=true in the [WebMethod] attribute:
OK. I’m going to stick with the page method approach for my particular scenario, since it will be code that I dont anticipate wanting to call from anywhere other than the website in which it resides.
Thanks again. Your blog is definitely on my greatest hits list.
i read awesome article, and i found it learn able much … thank u dave sir
Sorry but this article was gobblygook for me. I know how to write a web service and I know how to write a static method, how to use ViewState and Session state, and how to use an UpdatePanel, but the article is a bit over my head–what exactly is it saying? Actually the best reply for me was on Aug. 19, 2009 by Me, Myself and I. Bye.
OK, I think I get it now, it’s a follow-on of this article: http://encosia.com/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/
All in all, good article. I understand. The challenge I think it is that most often than not we need Page Methods logic to access control properties and other Page related data; so I find myself going “out of my way” to make this happen…
I’ve been searching for a while to find a good resource on jQuery with ASP.NET and always find ones speaking about MVC all the time. Finally I found your blog, and it’s a very valuable addition to my bookmarks now :)
Thanks
Greetings,
I just have two comments:
First: They are not made static because the ViewState is not posted. Pages are classes that have constructors and can be instantiated like any other class. If you look at HttpContext.Current.Handler during a web method call, you’ll find it an instance of your page. So what you mentioned is not the probable reason.
Maybe Microsoft did it this way to emphasize that you don’t need a Page instance in your web method.
The second is that, in one of your replies you suggested setting HttpContext.Current.Response.StatusCode to 401 or 403 to indicate that the user is not logged. Alas, this doesn’t work. If you set the status code and end the response or the user is trying to use the web method while he’s not logged, the response code you get is always 500 (internal server error). I posted about this in ASP.Net forums but didn’t get an answer.
At last, I’d like to thank you for your great and useful blog.
Nice, very nice explanation. Yesterday I had a debate on this topic, after finishing my speaking engagement on jQuery in ASP.NET session and have had some interesting remarks from audience. Interestingly, I read your blog about a year ago and have tried to find it again in order to give the URL to one friend of mine. You have explained it in details.
Nice article but didn’t find answer for my all questions…Thanks anyway
Great article & discussion. I’ve discovered something quite strange happening in my site that’s related to this discussion; when calling a static page method I’m seeing the page’s constructor being called first! (Not Page_Init or Page_Load, but the constructor). This seems really odd, as it doesn’t seem to follow the C++ model. I don’t know if C# always does this, or whether this is a by-product of how .NET handles a static page method request – I havne’t found anything about this online.
In my case I’ve moved the code in question out of the constructor (it shouldn’t really have been there in the first place), but I’m curious if anyone’s aware of this behavior.
Greetings,
Actually, your page class is instantiated. This is a feature of ASP.Net not C# (to call a static method, C# doesn’t require calling the constructor). If you look at HttpContext.Current.Handler during a static web method call, you will find it refers to an instance of your page. It’s ASP.Net who creates an instance of your page to handle the web method call.
Thanks Ashraf, so I’m not going crazy! Have you seen this documented anywhere? Its certainly an “unexpected” feature!
I think this is not documented anywhere. This behavior shouldn’t concern anyone, but because your page has a constructor, it may be annoying.
If you want to understand the internals, you may use reflector or ILSpy to examine the source code of System.Web.Handlers.ScriptModule and System.Web.Script.Services.ScriptHandlerFactory who should be responsible on passing web methods calls to static page methods.
Really informative
Yours is the best blog DAVE, keep it up
Really simplified explaination for complex topic. I created product catalog. I want to add to session each product. Is it possible to access session using page method? Thanks….
You can access Session in page methods as long as you set the EnableSession property of their WebMethod attribute. E.g.:
Note that this only applies to page methods. ASMX ScriptService methods enable session by default. That difference can be confusing at first, if you’re using both in various projects.
Hi. Actually, I’m sure it’s the other way round, i.e. enabled by default in page methods, but needs to be set ASMX methods.
You’re right about that. I’m not sure what I was thinking when I wrote that comment.
By the way, thank you for all your excellent posts!
No no no. The following sentence is incorrect: Each time a page is rendered to the browser, the Page serializes the state of its controls and then includes that information in the returned HTML, via a hidden form field named __ViewState.
It’s assertions like that which proliferate the misunderstanding of ViewState, which is one of the most misunderstood constructs in the ASP.NET platform. I cannot go into how ViewState works in one blog post comment. But I would suggest that you mention that ViewState tracks “changes” in a control’s state. And even that doesn’t cover all scenarios. It doesn’t just “maintain the state” of controls.
I’d recommend linking to another resource which explains ViewState and direct your readers there for more information. But leaving the post as is just proliferates one of the most common misunderstandings of what ViewState does.
Otherwise, nice post. Very informative.
Excellent Article.
Now, i’he been searching and cant find an answer to my problem.
I have a object that i must control via webpage, so in Global.asax.vb i put:
and i add it to Application attrib to be “avaiable” in all pages to use it,
Now i made a page with a div that when you click it, it calles for a $.ajax request to “default.aspx/ToogleLight”
So, ToogleLight() in default.aspx is defined as needed:
[System.Web.Services.WebMethod()]_ Public Shared</strong> Function ToogleLight(ByVal sender As Object, ByVal e As eventargs) As String Application("Engine").ToogleOutputDemo() 'Try to send a command to my object Return "yes!" End FunctionBut, of course, it tells me: “Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class” refeering to Application object,
so i have no idea how to access my app object from webMethod. Is there a place i can create an object and access it from my entire app/webservice solution, even from static methods as this ones? How to workaround this?
If i use a codebehind method to access Application object, then it works, but postback occurs, making all ajax useless.
Thanks! Im feeling in a chicken/egg problem.
You can use
HttpContext.Current.Applicationto access that object from within a static/shared method.You’re a master!
Thank u so much!!!!
Only a guru like you can write such a great article…
and +1 for giving me confidence by telling that there are people like me who find it easier to use page methods instead of going in to webservices business.
Now, if you can help me out here:
Is there any way I can access my checkbox list (asp.net server control), in my static pageMethod. For example, i used a static variable to access my querystirng(s) etc. but I can’t seem to find a way to use my checkbox list control, which needs to be populated and then updated using same Add/Update method.
Also is there a workaround for using Response.Redirect();
any suggestions/comments/thoughts are appreciated.
here is the code for reference:
Asad, you cannot do this. Page methods are not intended to manipulate a page controls, for this reason they’re made static, to emphasize that they don’t manipulate certain page instance. Page methods (and web service methods) are meant to accept some input and do certain processing then return output that can be consumed by client side JavaScript (or any other compatible client).
I think that your problem is candidate for UpdatePanels. Place the CheckBoxList in an UpdatePanel then place your code in a handler for an asynchronous request event.
Hi
gr8 article
keep it up
I am new to ASP.NET and page methods as well
I did’t understand what do you mean by “Page methods don’t work with User Controls”?
I mean that you can’t define a page method in an ASCX control’s code behind. It will compile, but you won’t be able to make requests to the .ascx/method URL.
Hi Dave
Great article. I was just wondering how I can get my static method to then call other business logic in my project. This entails me to create an instance of my business class, however, from what I remember I cannot create an instance of an object (class) from within a static method.
For example, just for simplicity. Say I have a class that loads an object that contains orders, then within that object I have a method that returns the total value of all order and I want to use ajax to display this…
This is the method that my jQuery ajax code will call. But from experience this will not work as far as I remember.
I suppose it comes down to me updating my existing applications to use Ajax, Object, Methods, Layers are already defined.
Hopefully this makes sense and you understand what I am asking.
Thanks
Mark
That will work.
What wouldn’t work, that you may have run into before, is something like this:
Also, don’t forget the
publicon the methods. They won’t work as “page methods” without that.Hi Dave
Thanks for your reply!
I have just quickly tried that out. One other question, how can I reference a control on the page. For example, a drop down list as it come up with an error as it’s a static method?
Thanks
Mark
You can’t. That’s basically the point of this post. The advantage of page methods is that they can be fast and light weight since they’re not encumbered by ViewState and the page life cycle. But, that also means an instance of the Page and its child controls never exists during the page method’s execution.
If you absolutely must have access to a WebControl during the AJAX request, you’ll need to use something like an UpdatePanel instead. Just keep in mind that you’ll be trading away significant performance for that convenience. If at all possible, figure out a way to work around that need by passing the dropdown’s client-side value as a parameter to the page method and/or setting the dropdown’s selected value on the client-side based on the result of the page method.
so i understand page method within a user control doesnt work…. so will it work if the page method is declared on a page hosting the user control? i know thats silly, but just curious.
oh wait, must the page method the javascript in the user control calls reside on a page that is hosting the user control? so say i have test1.ascx hosted in test1.aspx. can i in test1.ascx call test2.aspx.pageMethodName?
Yes, you can call a page method from anywhere. For all intents and purposes, they’re the same as ASMX ScriptServices with EnableSession defaulted to true.
interesting!! THanks Dave, for this blog and the replies!!
Just when I was coming to terms with *not* being able to access controls on the page from within static page methods:
From Ashraf Sabry:
“If you look at HttpContext.Current.Handler during a web method call, you’ll find it an instance of your page”
does that not mean that you could access the page’s controls then? I assume you cannot, but that fact makes me wonder again?
HttpContext.Current.Handler doesn’t contain anything useful inside a page method (or ever, really). HttpContext.Current is generally pretty handy in page methods, since it gives you access to the Application, Session, Cache, and other objects that you’re used to using from regular WebForms code, but there’s no Page instance there during a page method’s execution.
Thanks Dave… Great article by the way… I’m finding myself landing at encosia.com for answers more and more lately
HI
If im sending an invalid Json object like ( in jQuery)
data: ‘{aaa:”value”}’,
is there any middle class which resolve this “invalid json” ?
Also , How does the post to an ASP>NET page+function url , transfer the values to the function ? the url is not a page ! its a method ! so how does the iis knows to redirect it to the page -> method ?
I don’t have much experience working with this myself, but you can build your own JavaScriptConverter to apply custom logic during the [de]serialization process (including some facility for dealing with nearly-valid JSON). This is an example of using that approach: https://gist.github.com/6cfcdfdf2a117fa5e81b. Generally, I probably wouldn’t recommend doing that. It will take a lot of work and you’ll be reinventing quite a bit of existing functionality. It would probably be better to use one of the methods for extending $.ajax() and fix the data before it’s sent to the server.
I’ve forgotten the exact mechanism, but I believe the System.Web.Extensions.ScriptModule HttpModule is responsible for making the magic happen.
Awesome article for this i had been searching from a week thankq for ur support
Can convert the code to VB for me ?
Hi Dave,
Whether the pagemethods will use httpmodules and httphandlers(the default) as any other post backs(for eg: button click event on aspx page)
Thanks
Krishna