Ajax to Retrieve HTML Segments from Single ASPX

Have you ever wanted to have one ASPX file that can render normal content as well as dynamic content? The dynamic content can return HTML that utilizes ASPX server controls. The segment returned is not cloned from hidden markup preexisting on the page, but rather is foreign and new as far as the DOM is concerned. If so then follow these steps to create one relay station for all your content:

In the aspx file we define a section that is reserved for our ajax request:
Of course this page also has other HTML and script that will render/bind on page load:
The script wires up the button. Here, we are using jQuery’s $.load function:
Alternatively, you can use $.ajaxto make the request. Note that I do not have a contentType or performing json encoding:
So onto the code behind. These alternations handle the initial load request as well as any subsequent ajax requests:
If you walk through it you can see we are routing everything through the HandleCallbacks method. We check for an ajax request. If one is not declared then we exit gracefully and everything is rendered in the ASPX apart from our placeholders. If it is an ajax request we retrieve our data, assign it to the repeater, make it’s placeholder visible, then render the segment using a writer. The transformed markup is returned as part of the Response and we load it into a location of our choosing.

Download a DEMO.

Next, we will cover how to make ajax requests to separate aspx files.

Thanks.