Sanjeev Agarwal

Extending Web with ASP.NET
Reduce ASP.NET Page size and complexity using JQuery-Part 2

Reduce ASP.NET Page size and complexity using JQuery-Part 2 This is part 2 of my series for ASP.NET AJAX and JQuery comparison. You can read part 1 here. In my last 2 articles (Dynamically create ASP.NET user control using ASP.NET Ajax and Web Service and Dynamically create ASP.NET user control using JQuery and JSON enabled Ajax Web Service), I explained how to access JSON data from ASP.NET AJAX script service using ASP.NET AJAX client side framework and JQuery. In this post I will compare response/ request for these two implementations.

You can download the C# solution code here and VB.NET solution code here

For network monitoring, I used Firebug for Firefox 2/3.

Below is the image for ASP.NET Ajax implementation related files

With MS Ajax 


Below image show JQuery related implementation files

With JQuery 

See The Response Time for GetControlHtml Ajax Call in both implementation. The First GetControlHtml Ajax call is for GridView Control and second GetControlHtml Ajax call is for Login Control.  Same webservice method and controls are called in both implementations, so response size will be same.

It clear from the figure that in JQuery solution

  • AJAX call take less time
  • JavaScript Proxy File for web service is not required
  • ASP.NET AJAX client side framework files are not required
  • Less number of requests to the server
  • Overall transaction size is less

Please post your valuable feedback for this article. 

You can download the C# solution code here and VB.NET solution code here

kick it on DotNetKicks.com

Dynamically create ASP.NET user control using JQuery and JSON enabled Ajax Web Service

Dynamically create ASP.NET user control using JQuery and JSON enabled Ajax Web Service Please read my previous post Dynamically create ASP.NET user control using ASP.NET Ajax and Web Service to understand this approach. In this article I am doing the same thing using JQuery. Other code I already explain in previous post, so I will explain only JQuery related code in this article. To subscribe my blog through mail, Please click here subscribe blog by email.

You can download the VB.NET solution code here and the C# solution code here

Dynamic control creation using JQuery is more fun and easy. Here is sample request to access JSON enabled web service using JQuery.

function getJsonAjaxObject(webServiceURL, jsonData) {

 $.ajax({

  type: "POST",

  contentType: "application/json; charset=utf-8",

  url: serviceURL,

  data: jsonData,

  success:

   function(msg){

   //execute code related to success of web service

   },

  error:

   function(XMLHttpRequest, textStatus, errorThrown){

      //execute code related to failier of web service

   }

 });

}


Few thing you need to consider when you are accesing ASP.NET webservice through JQuery.
  • Request verb Type
  • Content- length with IIS6+
  • Default contentType
  • JSON object formatting
  • Maximum length exceed exception

I am explaining these issues and workaround to make JQuery work fine with ASP.NET Ajax enabled web service.

Request action Type

ASP.NET Ajax enabled web service by default only allows the HTTP POST verb to be used when invoking web service methods using JSON, which means you can't inadvertently allow browsers to invoke methods via HTTP GET. Workaround for this issue is to use "POST" verb for request.

Content- length with IIS6+

Most installations of IIS6+ require a content-length be provided with all POST requests, even if there is no content (POST data). The content-length for a request with no data should be 0, but jQuery doesn’t set that header automatically unless there is a data parameter. The workaround for this issue to use an empty JSON object as a parameter on read-only requests.

for example data: "{}"

This will cause jQuery to correctly set a content-length, while your web service will ignore the empty parameter and treat the request as read-only. 

Default contentType 

ASP.NET AJAX enabled webservice requires a Content-Type header to be set to "application/json" for invocations to AJAX web services.  JSON requests that do not contain this header will be rejected by an ASP.NET server. For JQuery Ajax request you need to mention content type as application/json.

for example contentType: "application/json;charset=utf-8"

JSON object formatting

If you directly provide a JSON object as the data parameter for an JQuery Ajax call, jQuery will attempt to serialize the object instead of passing it on to your web service and you will get invalid JSON primitive exception.

Work around to this issue is to pass JSON data parameter as string, like this

data: "{'controlLocation':'~/Controls/GridView.ascx'}"

Maximum length exceed exception

When you are accessing large JSON object via script service you need to update maxJsonLength in web.config otherwise you will get "maximum length exceed" exception.

<system.web.extensions>

              <scripting>

                     <webServices>

        <jsonSerialization maxJsonLength="5000000" />

                     </webServices>

              </scripting>

       </system.web.extensions>


The C#/VB.NET code is same as my last post. The XHTML code is slightly changed to call JQuery function instead of ASP.NET AJAX. 

<%@ Page Language="C#" EnableViewState="false"  %>

<!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 id="head" runat="server">

    <title>With JQuery</title>

    <link type="text/css" href="StyleSheets/iGridView-classic.css" rel="stylesheet" />

    <link type="text/css" href="StyleSheets/iGridView-common.css" rel="stylesheet" />

    <script language="javascript" type="text/javascript"   src="Scripts/jquery-1.2.6.pack.js"></script>

    <style type="text/css">

        body

        {

            width:95%;

            padding-left:20px;

            font-family:Arial;

            font-size:10pt;

            padding-right:20px;

        }

    </style>

</head>

<body>

    <form id="form" runat="server">

        <input type="button" value="Load Customer Order" onclick="getData('ScriptService.asmx/GetControlHtml','~/Controls/GridView.ascx');" />

        <input type="button" value="Load Login" onclick="getData('ScriptService.asmx/GetControlHtml','~/Controls/LoginControl.ascx');" />

        <input type="button" value="Register New User" onclick="getData('ScriptService.asmx/GetControlHtml','~/Controls/NewUserControl.ascx');" />

 <div id="testDiv"></div>

    </form>

</body>

</html>

The JavaScript to call JSON enabled WebService is mentioned below

<script type="text/javascript">

function getData(serviceURL, controlLocation) {

 $.ajax({

  type: "POST",

  contentType: "application/json; charset=utf-8",

  url: serviceURL,

  data: "{'controlLocation':'" + controlLocation + "'}",

  success:

   function(msg){

     $('#testDiv').html(eval(msg));

     formatTable();

   },

  error:

   function(XMLHttpRequest, textStatus, errorThrown){

       alert( "Error Occured!" );

   }

 });

}

function formatTable(){

    //get all row in gridview table and set style/event/attribute on them

    $("div#testDiv tr")

    .addClass("data-row")

    .mouseover(function(){

    if(! isClickedStyleSet(this.className)){

    this.className = "row-over";}

    if(! jQuery.browser.mozilla){

    this.style.cursor ="hand";

    }})

    .mouseout(function(){

     if(! isClickedStyleSet(this.className)){

     this.className = "data-row" ;}

    })

    .click(

    function(){

      if(! isClickedStyleSet(this.className)){

    this.className = "row-select" ;}

    else{this.className = "data-row" ;}

    });

    //get all cell in gridview table and set style/event/attribute on them

    $("div#testDiv td")

    .addClass("data-row")

    .css("white-space", "nowrap")

    .css("vertical-align", "middle")

    .mouseover(function(){

    setTitle(this);

    });

}

       

function setTitle(object){

    //check browser type 

    if(jQuery.browser.mozilla){

        object.title = object.textContent;

    }

    else{

        object.title = object.innerText;

    }

}

function isClickedStyleSet(className){

    //if row is already clicked return true

    if(className == "row-select"){

    return true;

    }

    return false;

}       

</script>

Below is the screenshot of the initial page.

Gridview Effect 

When user clicks on "Load Customer Order", It will call the ScriptService.asmx/GetControlHtml Web Service method get the usercontrol html data, load in the 'testDIV' and format the table inside div to implement mouseover/mouseout, click and title functionality using JQuery.

Gridview Effect 

Same way user can clicks on "load login" button to load "User Login" form dynamically.

Gridview Effect 


To load any usercontrol you need to call "getdata" function with webservice url and control location.

for example getData('ScriptService.asmx/GetControlHtml', '~/Controls/GridView.ascx');.

Please post your valuable feedback for this article.

You can download the VB.NET solution code here and the C# solution code here

kick it on DotNetKicks.com

Dynamically create ASP.NET user control using ASP.NET Ajax and Web Service

Dynamically create ASP.NET user control using MS Ajax and Web Service Thanks for your tremendous response for my first post on asp.net blog Reduce ASP.NET Page size and complexity using JQuery-Part 1. Within last 10 days it's got more then 1500 views. To subscribe my blog through mail, Please click here subscribe blog by email.

In this post I will explain how to load ASP.NET user control dynamically using ASP.NET AJAX and Web Service. In next post I will explain the samething using JQuery. Lot of user asked me to mentioned examples in VB.NET, so in this article, I will explain code in both language C#/VB.NET.      

You can download the VB.NET solution code here and the C# solution code here

To make web UI dynamic and more responsive to the various situations and modes, several techniques are used by the developers like making irrelevant controls invisible, disabling unused controls. This technique makes you page complex and heavy in size. Dynamic user control is another story. With dynamic control creation you will get the unmatched flexibility and innovation with robustness. Using this technique you can add any usercontrol to any page as per demand without postback or update panel.

I am using the last post example and extending it to use this feature. In last post I created the gridview control and placed on the page, In this example I will create this control on page dynamically using web service and ASP.NET Ajax and enhance it to support tooltip, mouseover, mouseout and click effect using ASP.NET Ajax client side framework. 

Below is the screenshot of the initial page.

Gridview Effect 

When user clicks on "Load Customer Order", It will call the webservice get the usercontrol html data and load in the 'testDIV'.

Gridview Effect 

Same way user can clicks on "load login" button to load "User Login" form.

Gridview Effect 

the XHTML code of the page in mentioned below.  

<%@ Page Language="C#" EnableViewState="false" %>

<!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 id="head" runat="server">

    <title>With MS Ajax</title>

    <link type="text/css" href="StyleSheets/iGridView-classic.css" rel="stylesheet" />

    <link type="text/css" href="StyleSheets/iGridView-common.css" rel="stylesheet" />

    <style type="text/css">

        body

        {

            width:95%;

            padding-left:20px;

            font-family:Arial;

            font-size:10pt;

            padding-right:20px;

        }

    </style>

</head>

<body>

    <form id="form" runat="server">

        <asp:ScriptManager runat="server">

        <Services>

        <asp:ServiceReference Path="~/ScriptService.asmx" />

        </Services>

        </asp:ScriptManager>

        <input type="button" value="Load Customer Order" onclick="getData('~/Controls/GridView.ascx');" />

        <input type="button" value="Load Login" onclick="getData('~/Controls/LoginControl.ascx');" />

        <input type="button" value="Register New User" onclick="getData('~/Controls/NewUserControl.ascx');" />

        <div id="testDiv"></div>

    </form>

</body>

</html>


To use web service on page you need to mention it in ScriptManager.

<asp:ScriptManager runat="server">

<Services>

<asp:ServiceReference Path="~/ScriptService.asmx" />

</Services>

</asp:ScriptManager>


Also update maxJsonLength in web.config otherwise you will get "maximum length exceed" exception for large json data.

<system.web.extensions>

      &nb