tags:

views:

89

answers:

2

Hi, I have this question:

How could I call a codebehind method from jquery? I have a web page: (ForgetPass.aspx) with its respective codebehind (ForgetPass.aspx.cs). On the codebehind I have a public method:

public void ChangeSession(string strChangeSession)
    { some stuff... }

When I was working on MVC, calling that method was as simple as:

$.post("MyPageController/ChangeSession", { strChangeSession: 'yes' });

But now that I'm on aspx/C# I don't know how to call that method from jquery (or maybe I need to use [WebMethod] clause on the codebehind ??)

Thanks in advance.

A: 

There's a full run down here that explains the whole process :)

Yes you'll need [WebMethod] and it'll need to be static as well, read the tutorial for an explanation on these bits.

Based on your method names, you'll probably need this:

[WebMethod (EnableSession = true)] //Allows access to session state
public void ChangeSession(string strChangeSession)
{ some stuff... }
Nick Craver
A: 

Several way to accompli9sh this. Like above look at the .NET PageMethod/Webmehtods, its will show you how to build the Webmethods to be called,a nd calling them from javascript.

I've been switching away from .NET pre-built stufff, and go with straight jQuery ajax calls, its the same thing, but using jQuery you have a little more control over the call and what it returns.

jQuery.ajax({
    type: "POST",
    url: "edit.aspx/yourmethodname",
    data: "{yourmethodparam:" + somevar + "}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(response) {
        alert(response.d);
    }
error: function(err, response) {
    alert("error");
}
});

Its more complex, but you get more control over what type of object is returned, Json or text.

Remember, response.d the "d" is the json object if you decide to return more then just a simple type, like string or integer. You can return objects like lists and such. These will be converted to JSON objects. If it were simple type like an integer, then just 'response' would be the value.

If you decide to go more complex and use JSON return objects, watch the 'datatype' property, sometimes i found .NET retunring string objects that had to be convertred into JSON using, json2.js file - http://www.json.org/js.html. It thru me for a loop for a long time. I good sie that will explain JSON, cause thats what the PageMethod/WebMethods are really using.