pavanarya

Let us share the knowledge

Loading User Control Dynamically Using Jquery and Web Service

with 5 comments

Hi,

In this post let us see the process of loading a .Net UserControl dynamically using jquery and web service.

Step1: Let us create a empty website project.

Step2:Add a web usercontrol(.ascx) file. I an my example i am adding a new user control and naming it as LoginForm.ascx

My LoginForm.ascx contains a simple form with a username text box and a password field.


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Loginform.ascx.cs" Inherits="Loginform" %>
<div>
<form name="input" action="default.aspx" method="get">
Username:<input type="text" id="username" />
Password:<input type="password" id="password" />
</form>
</div>

Step3: Now let us add a web service to our web site project. In my case i am creating a web service and naming it as ConsumeUsercontrol.asmx.

Step4: Now add a web method and name it as RetriveWebControl()


public string RetriveWebControl() {

        Page pg = new Page();
string path=@"\LoadUserControlDynamically\LoginForm.ascx";
//Here path refers to the virtual path of the usercontrol
        UserControl control = (UserControl)pg.LoadControl(path);
        pg.Controls.Add(control);
        StringWriter output = new StringWriter();
        HttpContext.Current.Server.Execute(pg, output, true);
        return output.ToString();

    }

So in the above web method initially we are creating a Page object. Now we are trying to add a web user control to that page object. So in order to add the User Control to page we should load it from a virtual path.LoadControl() method is used to load a User Control from a virtual path. After getting the web control now we are supposed to add it to the page that we created.
Now we are having a page with a web user control in it. So the next step would be to retrieve the page’s html content as a string.

HttpContext.Current.Server.Execute(
IHttpHandler handler,
TextWriter writer,
bool preserveForm
)
So this execute method executes the handler provided, the textwriter is used to capture the output after executing the handler. preserver form is used to specify whether to clear querystrings or not.
The reason behind passing page object to Execute method even though it accepts IhttpHandler as input is Page object implements the IHttpHandler.
So the web method RetriveWebControl returns the html content of the web user control
Step5: Now add a aspx page in which we want to consume the user control dynamically.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="useControl.aspx.cs" Inherits="useControl" %>

<!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 src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
        <script>
            function pavan() {
                $.ajax({
                    type: "POST",
                    url: "ConsumeUsercontrol.asmx/RetriveWebControl",
                    data: "",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        $("#usercontrolcontent").html(response.d);
                    }
                });
            }
        </script>
</head>
<body onload="pavan()">
    <form id="form1" runat="server">
    <div id="usercontrolcontent">

    </div>
    </form>
</body>
</html>

So in the body load we are calling a java script function called pavan().
Inside the function pavan() we are making a jquery ajax call.
$.ajax() accepts the following parameters.
1.Type: Type of request we are performing either Get o Post
2.url:The webservice url and after the slash ‘/’ we should provide the web method we want to call. So in our case the url will be “ConsumeUsercontrol.asmx/RetriveWebControl”.
3.data: Parameters to the web method
4. Content type
5.Datatype: either Jason or XML.
6. Here Success is the call back function that is if the ajax call is success then it will execute the code in the Success block. Similarly there is a callback function for error too.
7.So inside the success call back function we are appending the HTML content that we got from the web method to the div tag with id “usercontrolcontent”.

Thanks,
pavan

About these ads

Written by pavanarya

November 21, 2011 at 5:29 pm

Posted in Asp.net, Jquery

5 Responses

Subscribe to comments with RSS.

  1. Thank you…..

    Keval Mehta

    August 16, 2012 at 6:34 pm

    • its giving an error
      The type or namespace name ‘Page’ could not be found (are you missing a using directive or an assembly reference?)

      on following line
      Page pg = new Page();

      erum

      April 14, 2013 at 10:11 am

      • Hi Erum..If possible can you mail me the zip file that contains your dummy proj where you are getting the error. That helps me a lot to find the error quickly.

        pavanarya

        April 14, 2013 at 8:24 pm

      • Date: Sun, 14 Apr 2013 15:54:31 +0000 To: emirza_pk@hotmail.com

        Erum Mirza

        April 16, 2013 at 2:49 pm

      • using System.Web;
        using System.Web.UI;
        using System.Web.UI.WebControls;

        Add Following in CS File

        Vijay

        April 15, 2013 at 4:23 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 69 other followers

%d bloggers like this: