jQuery - Load ASP.Net User Control Dynamically

In this post, find jQuery code to load ASP.NET user control dynamically using jQuery and ajax together. To achieve this, we need to declare a WebMethod on server side which actually adds the user control to a Page class object. And using jQuery and Ajax, call this WebMethod and append the respond to any DOM element. The response will be content of User Control.

Below ASP.NET code, declares a WebMethod named "LoadUserControl". This method creates an object of Page class and then add the UserControl to Page class object. And then using Server.Execute method executes the page on the server in the current directory and receives the output from the page through the StringWriter object writer. It writes the HTML stream received from writer to the HTTP output stream.
[WebMethod]
public static string LoadUserControl()
{
  using (Page objPage = new Page())
  {
     UserControl uControl = 
                         (UserControl)objPage.LoadControl("TestUC.ascx");
     objPage.Controls.Add(uControl);
     using (StringWriter sWriter = new StringWriter())
     {
         HttpContext.Current.Server.Execute(objPage, sWriter, false);
         return sWriter.ToString();
     }
  }
}
And below is jQuery code to make an ajax request on button click and then append the response received from WebMethod to any DOM element to render the content of User Control. Also read "Execute/Run multiple Ajax request simultaneously"
$(document).ready(function () {
    $("#btnLoadControl").on("click", function (e) {
        $.ajax({
            type: "POST",
            url: "Default.aspx/LoadUserControl",
            data: "",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                $("#dvUControl").append(r.d);
            }
        });
        e.preventDefault();
    });
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..