Handling ajax request in WebForms

Elegant way to do AJAX in WebForms

In case you want to add JQuery Ajax calls to your page, you would basically need to add one more page which will be invoked with Ajax call.

In order to reduce number of physical pages you can reuse the same page, but make it act differently for normal GET/POST HTTP request and totally different for Ajax GET/POST HTTP request.

To determine whether request is AJAX or not you can use extension method described in this article.

The main idea is to render one content for normal and one for AJAX request. For this purpose we use placeholder for rendering AJAX content.

Handling of request should be done on Page_Init handle.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Asp.Net;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        if (Request.IsAjaxRequest())
        {
            Response.Clear();
            StringWriter sw = new StringWriter();
            this.phAjaxContent.Visible = true;
            this.phAjaxContent.RenderControl(new HtmlTextWriter(sw));
            Response.Write(sw.ToString());
            Response.End();
        }
    }
}
    

Extension method IsAjaxRequest is coming from custom library Asp.Net which I build and which is contained in attachment for this article. This extension method is described in this article. You can add it it to you own dll, compile it and use the same way it is used here.

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article