Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to load Web User Control using jQuery and WebMethod in ASP.NET

Author: Rachel Nicole
Download Source Code : 1386_LoadUserControlUsingJQuery.zip

The purpose of this article is to explain how we can load Web User Control using WebMethod and jQuery.

 

We can load a Web User Control dynamically using WebMethod and jQuery and can add it to ASP.NET page. We can pass Web User Control as parameter of WebMethod in client side code and can load user control using this WebMethod. I will create a List of Employee class in Web User Control and bind it to GridView control then I will create a WebMethod in my code file and call this WebMethod using client side code by providing Web User control as parameter.

Let’s see how we can load Web User Control using WebMethod and jQuery.

  1. Open Visual Studio 2010
  2. File > New > Web Site
  3. Visual Basic or Visual C#  > ASP.NET Empty Web Site
  4. Right click on web site > Add New Item > Web Form
  5. Right click on website > New Folder (Name the folder as “Scripts”). Download jQuery and jQuery autocomplete plug-in and include below files in this folder.

    jquery-1.4.1.min.js
     
  6. Add a <script> tag in between <head> tag of Default.aspx page. You have to give reference for jQuery as below.

    <head runat="server">
        <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
    </head>
     
  7. Right click on web site > Add New Item > Web User Control (Name the Web User Control as “EmployeeWebUserControl.ascx”).
  8. Add a GridView control in EmployeeWebUserControl.ascx

    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>

     
  9. Write code below in EmployeeWebUserControl.ascx.cs or EmployeeWebUserControl.ascx.vb

    C#

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
     
    public partial class EmployeeWebUserControl : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            GridView1.DataSource = GetEmployees();
            GridView1.DataBind();
        }
     
        public static List GetEmployees()
        {
            List list = new List();
     
            list.Add(new Employees { ID = 1, FirstName = "Pedro", LastName = "Afonso" });
            list.Add(new Employees { ID = 2, FirstName = "Lesley", LastName = "Brown" });
            list.Add(new Employees { ID = 3, FirstName = "Maria", LastName = "Larsson" });
     
            return list;
        }
     
        public class Employees
        {
            private int id = 0;
            private string fName = "";
            private string lName = "";
     
            public int ID
            {
                set
                {
                    this.id = value;
                }
                get
                {
                    return this.id;
                }
            }
     
            public string FirstName
            {
                set
                {
                    this.fName = value;
                }
                get
                {
                    return this.fName;
                }
            }
     
             public string LastName
            {
                set
                {
                    this.lName = value;
                }
                get
                {
                    return this.lName;
                }
            }
        }
    }
     
    VB.NET

    Partial Class EmployeeWebUserControl
        Inherits System.Web.UI.UserControl
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
            GridView1.DataSource = GetEmployees()
            GridView1.DataBind()
        End Sub
     
        Public Shared Function GetEmployees() As List(Of Employees)
            Dim list As New List(Of Employees)()
     
            list.Add(New Employees() With {.ID = 1, .FirstName = "Pedro", .LastName = "Afonso"})
            list.Add(New Employees() With {.ID = 2, .FirstName = "Lesley", .LastName = "Brown"})
            list.Add(New Employees() With {.ID = 3, .FirstName = "Maria", .LastName = "Larsson"})
     
            Return list
        End Function
     
        Public Class Employees
            Private m_id As Integer = 0
            Private fName As String = ""
            Private lName As String = ""
     
            Public Property ID() As Integer
                Get
                    Return Me.m_id
                End Get
                Set(ByVal value As Integer)
                    Me.m_id = value
                End Set
            End Property
     
            Public Property FirstName() As String
                Get
                    Return Me.fName
                End Get
                Set(ByVal value As String)
                    Me.fName = value
                End Set
            End Property
     
            Public Property LastName() As String
                Get
                    Return Me.lName
                End Get
                Set(ByVal value As String)
                    Me.lName = value
                End Set
            End Property
        End Class
    End Class
     
     
    I have created a class Employee and get and set properties for id, first name and last name. Then I have created a function GetEmployees() which returns a list of Employee and added three items to list. In the Page Load event of the Web User Control, I have bound GridView control to GetEmployees() function.
     
  10. Write a WebMethod in Default.aspx.cs or Default.aspx.vb

    C#

    [WebMethod]
    public static string GetUserControl(string userControl)
    {
        Page page = new Page();
        UserControl control = (UserControl)page.LoadControl(userControl);
        HtmlForm form = new HtmlForm();
        form.Controls.Add(control);
        page.Controls.Add(form);
        StringWriter writer = new StringWriter();
        HttpContext.Current.Server.Execute(page, writer, false);
        return writer.ToString();
    }
     
    VB.NET
     
    <WebMethod()> _
    Public Shared Function GetUserControl(ByVal userControl As String) As String
        Dim page As New Page()
        Dim control As UserControl = DirectCast(page.LoadControl(userControl), UserControl)
        Dim form As New HtmlForm()
        form.Controls.Add(control)
        page.Controls.Add(form)
        Dim writer As New StringWriter()
        HttpContext.Current.Server.Execute(page, writer, False)
        Return writer.ToString()
    End Function
     
    In WebMethod, I have created Page object and called the LoadControl() method to load control. Then I have added control to HtmlForm and form to page. At the end of WebMethod, I have called the Execute() method and provided the page object and writer object and returned the writer object.
     
  11. Write code below in Default.aspx page

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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 runat="server">
       
        <title></title>
       
        <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
       
           <script type="text/javascript">
       
               $(document).ready(function () {
       
                   $('#Button1').click(function () {             
       
                       var control = "EmployeeWebUserControl.ascx";
       
                       $.ajax({
       
                           type: "POST",
       
                           url: "Default.aspx/GetUserControl",
       
                           data: "{userControl:'" + control + "'}",
       
                           contentType: "application/json; charset=utf-8",
       
                           dataType: "json",
       
                           success: function (r) {
       
                               $('#div1').html(r.d);
       
                           }
       
                       });
       
                   });
       
               });     
       
       </script>
       
     
       
    </head>
       
    <body>
       
        <form id="form1" runat="server">
       
        <div>
       
            <input type="button" id="Button1" value="Load Data from User Control" />
       
            <div id="div1"></div>
       
        </div>
       
        </form>
       
    </body>
       
    </html>
     
    Client side is simple. I have created an input field button and a div in between form tag. In between head tag, I have written two script tags. First script tag is for reference of jQuery. In second script tag I have used jQuery to write client side code to load Web User Control. I have got the button id, set the type and content type and provided the URL of WebMethod. I have also provided WebUserControl name in “data” which will be passed as parameter of WebMethod. When button is clicked, the function will get the data load into the div tag of the page.

    You have to change first line of above code which is page directive for C#. The VB page directive will be:
     
    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
     
  12. Now you can see it in your browser.
   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to call SQL Server User Defined Function in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net