Search code examples
javascriptc#asp.netasmx

Web method works only if marked as static, otherwise doesn't


Code-behind:

[ScriptMethod]
[WebMethod]
public string SavePassword(string password, string username, string resellerId, string isPasswordReset)
{    
    return null; // For example
}

javaScript:

$.ajax({
     type: 'POST',
     url: 'login.aspx/SavePassword',
     data: '{"password":"' + passwordInput + '","username":"' + hidusrname + '","resellerId":"' + hidResellerId + '","IsPasswordReset":"' + hidIsPasswordReset + '"}',
     contentType: 'application/json; charset=utf-8',
     dataType: 'json',
     success: function (result) { },
     error: function () { alert('error');
  }

});

public static string SavePassword() works, public string SavePassword() does not work.

If i change webmethod as static it works if i don't it does not work.

How can i webmethod without static method in my page ?


Solution

  • Web methods have to be static. It is impossible to have an instance web method. The reason is the way they are designed.

    Web methods do not have any state, or any relation to the rest of the page. There is no reason to go through the whole ASP.NET pipeline of creating a page object and all its life cycle. They also do not need to process the viewstate field that is required for page object creation. And as methods totally detached from the page object, they have to be declared as static to function properly.

    In return web methods offer a very good performance compared to regular ASP.NET pages or update panels.