Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why WebMethod declared as Static?

I declared a WebMethod in my default.aspx.cs file..

[WebMethod]
public static void ResetDate()
{
   LoadCallHistory(TheNewDate.Date);
}

Why must the WebMethod method be declared static?

like image 802
Gaurav Gupta Avatar asked Aug 27 '13 10:08

Gaurav Gupta


People also ask

Can WebMethod be non static?

You can't. If it's in the code behind it must be static for you call it directly via Ajax. Alternatively use a webservice/webmethod, or wcf.

What is the use of WebMethod in asp net?

The WebMethod attribute is added to each method we want to expose as a Web Service. ASP.NET makes it possible to map traditional methods to Web Service operations through the System.

Why we use WebMethod?

webMethods.io Integration enables you to automate tasks by connecting apps and services, such as Marketo, Salesforce, Evernote, and Gmail. It lets your favorite apps exchange data and talk to each other seamlessly, and eliminates the need to hire expensive developers to build your favorite integrations.

What is PageMethods in asp net?

A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript. Let us explore PageMethods with an example.


1 Answers

They're static because they are entirely stateless, they don't create an instance of your page's class and nothing is passed to them in the request (i.e. ViewState and form field values).

HTTP is stateless by default, ASP.Net does a lot of stuff in the background with ViewState, Session, etc. during a standard page request to make life easier for developers.

When a web method is called through AJAX, the page isn't sending all the necessary form data ASP.Net embeds in a page to keep track of request state because it would make web methods too slow; and if you need to do a lot of processing you should move it out to a dedicated web service instead.

You can get access to methods on the page using HttpContext.CurrentHandler which is explained in more detail here and also the current user if you need it via HttpContext.Current.User.

There's an excellent article here explaining this in more detail.

like image 71
Sean Airey Avatar answered Oct 11 '22 20:10

Sean Airey