Home   Subscribe   Linkedin
  Archive Contact  

Loading usercontrol on page without postback

In one of the projects I have developed on client side(jquery,Html),I used this approach of loading the user control without getting any page postback.

If you are naïve to jquery ajax calling code behind method then you have to go through my previous blog 'http://blogs.effectlabs.com/post/2012/02/24/jquery-ajax-calling-Wcf-service-or-some-method-in-Code-behind-from-Client-Side.aspx.

Now here I am adding two user controls one by one on my aspx page(Default.aspx) depending on which button is clicked.

The same javascript method which I have used in previous blog to call code behind method is used i.e

function ClientProxyDateFormatted(methodName, paramArray, successFunction, errorFunction) {
    var pagePath = window.location.pathname;
    var paramList = '';

    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '"' + ':' + '"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    var length = pagePath.length;
    if (pagePath.substring(length - 1, length) == "/") {
        pagePath += "Default.aspx";
    }
    else if (pagePath.substring(length - 5, length) != ".aspx") {
        pagePath += "/Default.aspx";
    }
    $.ajax({
        type: "POST",
        url: pagePath + "/" + methodName,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "text",
        processData: false,
        success: function (msgg) {
            var msg = JSON.parse(msgg, function (key, value) {
                var a;
                if (value != null) {
                    if (value.toString().indexOf('Date') >= 0) {
                        a = /^\/Date\((-?[0-9]+)\)\/$/.exec(value);
                        if (a) {
                            var dt = new Date(parseInt(a[1], 10));
                     return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
                        }
                    }
                    return value;
                }
            });
            successFunction(msg);
        },
        error: function (xhr, status, error) {
            errorFunction(xhr, status, error);
        }
    });
    return false;
}

Now add this method or reference to the javascript file(common.js in my case) in which this method is present on your aspx page.I have used two user controls namely MyUserControl1.ascx and MyUserControl2.ascx which are added on main page on button ‘btnLoadControl1’ and button ‘btnLoadControl2’ clicks respectively. After this write the code below on your aspx page under script tag.

  <script type="text/javascript"> var globalUserControlList= new Array();
        $(document).ready(function () {
            $('#btnLoadControl1').click(function () {
                var userControl = this.id;
                $('#wrap>div').hide();
                if ($.inArray(userControl, globalUserControlList) >= 0) {
                    $('#ucFirst').show();
                }
                else {
                    globalUserControlList.push(userControl);
                    LoadViewMyProfileUc(userControl);
                }

            });

            $('#btnLoadControl2').click(function () {

                var userControl = this.id;
                $('#wrap>div').hide();
                if ($.inArray(userControl, globalUserControlList) >= 0) {
                    $('#ucSecond').show();

                }
                else {
                    globalUserControlList.push(userControl);
                    LoadViewMyProfileUc(userControl);
                }
            });
        });
        function LoadViewMyProfileUc(userControl) {
            ClientProxyDateFormatted("LoadUserControl", ['controlId', userControl],
            function (msg) { succesfulLoadUserControl(msg); }, function (xhr, status, error) 
            { errorLoadUserControl(xhr, status, error); });
        }
        function succesfulLoadUserControl(msg) {
            $('#wrap').append(msg.d);
        }
        function errorLoadUserControl(xhr, status, error) { 
        alert('Error Loading UserControl')
        }
    </script> 

 

Here Array globalUserControlList keeps the track of user controls already loaded.If they are already present on aspx page ,it does not reload them,but just show them by using jquery method (.show()) otherwise it calls the method LoadViewMyProfileUc(userControl) which contains one parameter i.e clicked button’s id which tells us the user control to be loaded.LoadUserControl is the method in code behind which decides which user control to load.

Add Code below to some div on your aspx page

 <div id='mainDiv'> 
<
div id='buttonDiv'>
<
a id='btnLoadControl1'>Load First</a>
 <
a id='btnLoadControl2'>Load Second</a>
 </
div>
<
div id='wrap'>
</
div>
 </
div>

 

Below is the Code in .cs file

[WebMethod]
       public static string LoadUserControl(string controlId)
       {
           switch (controlId)
           {
               case "btnLoadControl1":
                   return RenderControl("~/UserControls/MyUserControl1.ascx");
               case "btnLoadControl2":
                   return RenderControl("~/UserControls/MyUserControl2.ascx");
              

           }


           return null;
       }

       public static string RenderControl(string controlName)
       {
           var page = new Page();
           var userControl = (System.Web.UI.UserControl)page.LoadControl(controlName);
           userControl.EnableViewState = false;
           page.Controls.Add(userControl);
           var textWriter = new StringWriter();
           HttpContext.Current.Server.Execute(page, textWriter, false);
           return textWriter.ToString();
       }

We are using the string writer class in method RenderControl to read the html of user control and return this html to Successful Function of the client side method on aspx page.The html is contained in msg.d of method succesfulLoadUserControl(msg) which we append to our container div (wrap).

Below are the snap shots of successful loading of User Controls

snap1_thumb[3][4]  snap2_thumb[8]

 I have attached a sample project below 

LoadingUserControl.zip (265.93 kb)

Posted by: Rishabh Toshniwal

Categories: Ajax, ASP.NET, C#, Javascript, Jquery

Tags: , ,

jquery ajax calling Wcf service or some method in Code behind from Client Side

If you are looking for some mechanism to call Wcf service from client side,here is the simple and tested solution for that.

Put the following script in some javascript file say common.js

function ClientProxyDateFormatted(methodName, paramArray, successFunction, errorFunction) {
    var pagePath = window.location.pathname;
    var paramList = '';

    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '"' + ':' + '"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    var length = pagePath.length;
    if (pagePath.substring(length - 1, length) == "/") {
        pagePath += "Default.aspx";
    }
    else if (pagePath.substring(length - 5, length) != ".aspx") {
        pagePath += "/Default.aspx";
    }
    $.ajax({
        type: "POST",
        url: pagePath + "/" + methodName,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "text",
        processData: false,
        success: function (msgg) {
            var msg = JSON.parse(msgg, function (key, value) {
                var a;
                if (value != null) {
                    if (value.toString().indexOf('Date') >= 0) {
                        a = /^\/Date\((-?[0-9]+)\)\/$/.exec(value);
                        if (a) {
                            var dt = new Date(parseInt(a[1], 10));
                            return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
                        }
                    }
                    return value;
                }
            });
            successFunction(msg);
        },
        error: function (xhr, status, error) {
            errorFunction(xhr, status, error);
        }
    });
    return false;
}

Code behind should be like as below.Here I am calling method ‘CallWcfMethod’ .Remember to add [WebMethod] above the method to be called and 

make the method public static.

[WebMethod]
        public static string CallWcfMethod(string myParameter)
        {
            return "Hello" + " " + myParameter;
            //You can Call your Wcf Method here }

Now  add reference of common.js (defined above)file on aspx page and write the below code .In my case I have written it on MyPage.aspx page .Here I am calling  method named ‘CallWcfMethod’ in code behind   on button click.Here I am passing one string type parameter to code behind method and code behind method is concatenating ‘Hello’+myParameter(parameter I have passed).The client side method used is

ClientProxyDateFormatted(“CodeBehindMethodName”,[“ParameterName”,paramterValue],SuccessFunction(msg),FailureFunction(error))

Things to note here

1)Your parameter name should be exactly the same as you have written it in code behind(in my case I have used ‘myParameter’).

2) After Successful calling of method ,Success function is called which has a paramter msg where msg.d contains the data that is returned  from Code behind method or Wcf Service.

3)In case when there is some error in calling method Failure function is invoked.

 

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyPage.aspx.cs" Inherits="LoadingUserControl.MyPage" %> 
<!
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">
<
script src="Scripts/jquery-1.4.1.min.js" type="text/javascript">
</
script>
<
script src="Scripts/Common.js" type="text/javascript"></script>
<
title>Call Wcf</title>
<
script type="text/javascript">
 
$(document).ready(function () { $('#btnCallWcf').click(function () { var parameterValue = 'User'; ClientProxyDateFormatted("CallWcfMethod", ['myParameter', parameterValue], function (msg) { succesfulCallWcf(msg); }, function (xhr, status, error) { errorCallWcf(xhr, status, error); }); }); }); function succesfulCallWcf(msg) { alert('The result is ' + msg.d) } function errorCallWcf(xhr, status, error) { alert('Error'); } </script>
 </
head>
<
body>
<
form id="form1" runat="server">
 <
div>
 <
div>
<
a id='btnCallWcf'>Call Wcf</a>
 </
div>
 </
div>
 </
form>
 </
body>
 </
html>

Here is the snapshot on successful method call

Snapshot

I have attached all the necessary code for your ease.

CallWcf.zip (2.37 kb)

Posted by: Rishabh Toshniwal

Categories: Ajax, ASP.NET, C#, Javascript, Jquery

Tags: ,