views:

78

answers:

2

Recently I have been working on project that heavily relies on AJAX calls. In the past most of these calls have been using there own aspx page to post to eg. AJAXgetResults.aspx. After doing some research I saw some examples using jquery's .ajax function and webmethods in the codebehind. I guess my question boils down to. Is there any performance gain/loss by going the webmethod route? I would assume it would still be as secure as the page that it is on, right? Any other suggestions are more than welcome! Thanks!

+1  A: 

I guess it depends on the level of control you want to have over what happens during the AJAX call. Webmethods will certainly work, but what I've been using in a recent project is creating a .ASHX handler per distinct functionality you want to expose to your AJAX calls. You still have access to any context variables such as request, response, querystring, session etc and the logic is nicely encapsulated away from any pages and you also don't get the overhead of a 'normal' page processing and life cycle, which should improve performance.

Just be careful to set your caching levels, because ASHX handlers seem very 'cacheable' by default.

Example, ashx to retrieve all employees for a certain position and return the results in JSON format:

public class GetEmployeesForPosition : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            context.Response.Clear();
            context.Response.AddHeader("Pragma", "no-cache");
            context.Response.AddHeader("Expires", "-1");

            var position = new Entity.Model.Position { Code = context.Request.QueryString["code"] };
            var language = new Language { Key = context.Request.QueryString["language"] };

            var list = new EmployeeManager().GetForPosition(position, language);
            var employeeMenuList = new List<KeyValuePair<string, string>>();
            foreach (var emp in list)
            {
                var item = new KeyValuePair<string, string>(emp.Person.Number, emp.Person.DisplayName);
                employeeMenuList.Add(item);
            }

            var json = JsonSerializer.ToJson(employeeMenuList);
            context.Response.Write(json);
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
Sam
Edited with an example.
Sam
+1  A: 

If you application relies heavily on AJAX (XHRs more generally) I would look into WCF Rest and returning results in JSON. You'll reduce bandwidth consumed and generally get a performance improvement, I find the WCF serialization and authentication vastly superior to using a page as a service, also. Generally your performance should improve by changing these pages to services.

marr75