Friday, 26 November 2010

AJAX - ASP.NET : Call WebMethod defined in User Control

If you have welcomed the joys of AJAX into your ASP.NET application, you may or may not have come across this problem.

With AJAX calls, I tend to store the WebMethod within the ASPX pages rather than services; so that I can keep my logic relating to the page separate from everything else. There is nothing worse than having a global service with tens or hundreds of methods in that get called every time. (well maybe there is, but you see my point!)

However, where user controls are concerned, we have a slight problem. A limitation of the framework prevents us from calling a WebMethod defined in a User Control (as of .NET 3.5). Some people have suggested adding a proxy method to the page which hosts the user control to call a method within the user control. This is wrong on many levels as it ties the page to the control and defeats the purpose or re-usability with ease.

Instead of a page method, add a service method instead. Either an ASMX or an SVC, it doesn't really matter. These are useful to hosting WebMethods that can be reused by many pages within the application OR user controls (which are re-usable by design anyway).

No comments: