How to Load Page Content Dynamically Using ASP.NET jQuery


Requirement

I have a web page and I want to add some content to it. The content page is a different page.

I can't use
<iframe></iframe> tag.

Solution

jQuery has a .load() method. Using this you can load the page dynamically.

Step1: Create a page named DynamicPage.aspx like:

<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="DynamicPage.aspx.cs" Inherits="DynamicPageContent.DynamicPage" 
%>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
Transitional//EN"
 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<
body>
    <form id="form1" runat="server">
    <script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <div id="dynamic">
    </div>    
    <script language="javascript" type
="text/javascript">
        $(document).ready(function () {
            loadDynamic();
        });
        function loadDynamic() {
            $("#dynamic").load(
"Default.aspx,function (content) {               
                $(this).hide().fadeIn("slow");
                return false;
            });
        }
    </script
>
    </form>
</body>
</
html> 

Step 2: Create a content page like:

<%
@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="Default.aspx.cs" Inherits="DynamicPageContent.Default" 
%> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
Transitional//EN"
 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<
body>
    <form id="form1" runat="server">
    <div>
        <fieldset>
            <legend>Lion</legend>
            <p>
                This is Dynamic Page Content loaded by jayendrasinh Gohil (Lion).
            </p
>
        </fieldset>
    </div>
    </form>
</body>
</
html> 

Step 3: Set the DynamicPage.aspx as a startup page. And run the application.

Your page output will be like:

pageload.gif

You can also pass a parameter to the content page:

function loadDynamic() {
    $("#dynamic").load("Default.aspx", { name: 'jayendra' }, function (content) {
        $(this).hide().fadeIn("slow");
        return false;
    });
}
 

And on the page load event of the content page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace DynamicPageContent
{
    public partial class Default : System.Web.UI.
Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Params["name"] != null)
                { 
                } 
            }
        }
    }
}