-->

How to add usercontrol dynamically in ASP.NET using Jquery.

Introduction

In this post, I am explain how to add usercontrol dynamically using JQuery in ASP.NET.

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Usercontrol.

Go to Solution Explorer > Right Click on Solution Explorer > Add > New item > Select Web User Control Under Web > Enter name > Add.

Step-3: Add a Webpage and Design for Add Usercontrol dynamically.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML Code
    
   <h3>Add Usercontrol Dinamically in ASP.NET</h3>
   <div>
       <input type="button" id="AddGadgets" value="Add Weather Gadgets" />
   </div>
   <div id="UpdatePanel">

   </div>
        

Step-4: Write Jquery code for add Usercontrol into page dinamically.


   
    <script src="Scripts/jquery-1.7.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#AddGadgets").click(function () {
                $.ajax({
                    url: "Default.aspx/AddGadGets",
                    type: "POST",
                    data: "",
                    contentType: "application/json; charset=utf-8",
                    success: OnSuccess,
                    error: OnError
                });
            });
        });
        function OnSuccess(data) {
            $("#UpdatePanel").html(data.d);
        }

        function OnError() {
            $("#UpdatePanel").html("Error!");
        }
    </script>


Step-5: Write a function in code behind page for get usercontrol as Json string.

   
    [WebMethod]
        public static string AddGadGets()
        {
            string content = "";
            Page pg = new Page();
            UserControl ucGadgets = (UserControl)pg.LoadControl("~/UCWeatherReport.ascx");
            pg.Controls.Add(ucGadgets);
            StringWriter sw = new StringWriter();
            HttpContext.Current.Server.Execute(pg, sw, true);
            content = sw.ToString();
            return content;
        }

Step-6: Run Application.



Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.