Asynchronous Method Calls to Code-Behind
One of the many things we’ve been trying to do at work lately is keep as much logic out of the UI as possible. We’ve been making extensive use of jTemplate to help us out on this: Specify an HTML file that you can pass a set of JSON data to, and it loads it up for you in the format you specify. Another technique we have been utilizing lately is the use of Web Service files: We are calling these the “controllers” of our project. Even though they aren’t controllers in the fullest sense of the definition, they are a step in the right direction. In any case, one particular flaw that we noticed in this system was that in some cases we were creating controllers for one usage only: The methods were only being called by a single ASPX page. We figured such methods should actually go in the code-behind instead of a separate class in this case.
It turns out that creating a code-behind method suitable for asynchronous calls is not very difficult. One merely has to declare the method to be both public and static. In addition, it must carry the WebMethod attribute.
namespace Project.UI
{
public partial class FooStuff : Page
{
// Hopefully not too much code here!
[WebMethod]
public static List<Foo> GetFoos()
{
// Asynchronous stuff here.
}
}
}
As you can see, you don’t even need to decorate the class FooStuff with the ScriptService attribute or even the WebService attribute. The only requirements are on the method itself. To invoke this method, we use a jQuery Ajax call.
$.ajax
({
type: 'POST',
url: './FooStuff.aspx/GetFoos',
data: '{}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
});
