| 1 comments ]

In this article I will explain how to consume a WCF / ASMX service using jQuery. The scope of the article is limited to creating & consuming different kind of services using jQuery. I have segregated this article into 7 topics based on the service consumption.

  1. Calling ASMX Web service using jQuery
  2. Calling WCF service using jQuery and retrieving data in JSON Format
  3. Calling WCF service using jQuery and retrieving data in XML Format
  4. Calling WCF service using jQuery and retrieving data in JSON Format (pass multiple input parameters) & ( Get multiple objects as output using DataContract)
  5. Calling WCF service using jQuery[ Get Method] and retrieving data in JSON Format
  6. Calling REST based WCF service using jQuery
  7. Streaming an image through WCF and request it through HTTP GET verb..

If you have never heard about jQuery or WCF or JSON, please learn it before dwelling into this article. The scope is limited to service creation and consumption.

In the below example I have used jQuery version 1.3.2 , you can download the same from http://jQuery.com/. This article demonstrates how our jQuery based browser app will retrieve the Provinces for supplied country. All the services are hosted in the same web application. Please download the source code to experiment the sample by yourself.

For calling the service we need to use the .ajax method of jQuery which makes XMLHttpRequest
to the server. In the below code section I have explained the key value pair attributes to be passed by marking comments on the right side of the attribute.

<script type="text/javascript" language="javascript" src="script/jQuery-1.3.2.min.js" "></script>

     <script type="text/javascript">

        var varType;
        var varUrl;
        var varData;
        var varContentType;
        var varDataType;
        var varProcessData; 

        function CallService() 
        {
                $.ajax({
                    type                : varType, //GET or POST or PUT or DELETE verb
                    url                   : varUrl, // Location of the service
                    data                : varData, //Data sent to server
                    contentType    : varContentType, // content type sent to server
                    dataType         : varDataType, //Expected data format from server
                    processdata    : varProcessData, //True or False
                    success            : function(msg) {//On Successfull service call
                    ServiceSucceeded(msg);                    
                    },
                    error: ServiceFailed// When Service call fails
                });
        }
    </script>
I have made the above method generic to use it for all different type of services which we are going to discuss.

Business Logic:

Business logic for below demonstrated service is quite simple, we store Country and Province details in a Name Value collection ,When a request supplies the country name it returns the provinces associated with it.

public class CountryProvinceBL
{
    NameValueCollection nvProvince = null;
    public CountryProvinceBL()
    {
        nvProvince = new NameValueCollection();
        nvProvince.Add("usa", "Massachusetts");
        nvProvince.Add("usa", "California");
        nvProvince.Add("india", "Tamil Nadu");
        nvProvince.Add("india", "Karnataka");
    }
    
    public string[] GetProvince(string Country)
    {  return nvProvince.GetValues(Country).ToArray();}

}


1. Calling ASMX Web service using jQuery


Step 1:

Create a web service and add the below code

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// Below line allows the web service to be called through HTTP protocol. 
[System.Web.Script.Services.ScriptService]
public class CountryProvinceWebService : System.Web.Services.WebService
{

    [WebMethod]
   //Business Logic returns the provinces for the supplied country
    public string[] GetProvince(string Country) 
    {  return new CountryProvinceBL().GetProvince(Country); }    
}

Step 2:

Invoke the below method on button click

unction CountryProvinceWebService() {
            varType              = "POST";         
            varUrl                 = "service/CountryProvinceWebService.asmx/GetProvince"; 
            //Pass country from drop down ddlCountry'
            varData               = '{"Country": "' + $('#ddlCountry').val() + '"}';
            varContentType  = "application/json; charset=utf-8";
            varDataType       = "json";varProcessData = true; CallService();
        }



Step 3:

On Success "ServiceSucceeded" will be called and it will populate the provinces dropdown with the values sent by the server.


function ServiceSucceeded(result) {
            var ProvinceDDL = document.getElementById("ddlProvince");
            for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
            var resultObject = result.d; // Constructed object name will be object.d //Button 
            for (i = 0; i < resultObject.length; i++) {
                    var opt = document.createElement("option"); opt.text = resultObject[i];
                    ProvinceDDL.options.add(opt)
                }
        }

2. Calling WCF service using jQuery and retrieving data in JSON Format


Step 1:

Define the Contracts in the interface ICountryProvinceWCFService

[ServiceContract]
public interface ICountryProvinceWCFService
{
    [OperationContract]
    [WebInvoke(Method = "POST",BodyStyle=WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]    
    string[] GetProvince(string Country);
}

Implement the contract in class CountryProvinceWCFService 

public class CountryProvinceWCFService : ICountryProvinceWCFService
{   
  // Call Business Logic to get provinces
    public string[] GetProvince(string Country)
    {return new CountryProvinceBL().GetProvince(Country); }
}

Step 2:

Define the configuration in web.config

a) enables the user to view the metadata through web browser and generate WSDL file

b) setting includeExceptionDetailInFaults = "true" allows the WCF service throw original error , it will be useful while debugging the application.

c) Adding to endpoint behaviour & webHttpBinding to binding enables the web programming model for WCF and allows the service to be accessible through web protocols.

d) Define contract and name of the service

Step 3:

Invoke the WCF service on the button click event


function CountryProvinceWCFJSON() {
            varType              = "POST";
            varUrl                 = "service/CountryProvinceWCFService.svc/GetProvince";
            varData              = '{"Country": "' + $('#ddlCountry').val() + '"}';
            varContentType = "application/json; charset=utf-8";
            varDataType      = "json"; varProcessData = true; CallService();
        }


On successful service invocation "ServiceSucceeded" will be called and the province value will get added to province drop down.


function ServiceSucceeded(result) {/
       var ProvinceDDL = document.getElementById("ddlProvince");
       for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
               // Constructed object name will be object.[ServiceName]Result // Button 2 & 3
              var resultObject = result.GetProvinceResult;
           for (i = 0; i < resultObject.length; i++) {
               var opt = document.createElement("option"); opt.text = resultObject[i];
               ProvinceDDL.options.add(opt)
           }       
   }

3. Calling WCF service using jQuery and retrieving data in XML Format

Step 1:


In operation contract set ResponseFormat to XML.

[OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped,ResponseFormat = WebMessageFormat.Xml)]
    string[] GetProvinceXML(string Country);

Then implement the service 

    public string[] GetProvinceXML(string Country)
    {  return new CountryProvinceBL().GetProvince(Country); }

Use the web.config, defined in Figure 1 .

Step 2:

Invoke the WCF service on the button click event, Make sure you set the expected data type as XML

function CountryProvinceWCFXML() {
            varType              = "POST";
            varUrl                 = "service/CountryProvinceWCFService.svc/GetProvinceXML";
            varData              = '{"Country": "' + $('#ddlCountry').val() + '"}';
            varContentType = "application/json; charset=utf-8"; 
            varDataType      = "xml";  varProcessData = true; CallService();
        }

Step 3:

On successful service invocation "ServiceSucceeded" will be called and the province value will get added to province drop down.

function ServiceSucceeded(result) {
              var ProvinceDDL = document.getElementById("ddlProvince");
              for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }
            //Below jQuery code will loop through the XML result set
              $(result).find("GetProvinceXMLResult").children().each(function() {
                  var opt = document.createElement("option"); opt.text = $(this).text();
                  ProvinceDDL.options.add(opt)
              });          
          }

4. Calling WCF service using jQuery and retrieving data in JSON Format (pass multiple input parameters) & ( Get multiple objects as output using DataContract)

In this example Country and Browser type will be passed as input parameter to the WCF service in JSON format, Upon receiving the values the service will send back provinces for the passed country and some comments for the browser information.

Step 1:

Define Data contract and service contact for the service

[DataContract]
public class CustomData
{
    [DataMember]
    public String BrowserInfo;
    [DataMember]
    public String[] ProvinceInfo;
}

  [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
    CustomData GetProvinceAndBrowser(string Country, string Browser);


And implement the contract in your service call

    public CustomData GetProvinceAndBrowser(string Country, string Browser)
    {
        CustomData customData = new CustomData();
        customData.ProvinceInfo = new CountryProvinceBL().GetProvince(Country);
        if (Browser == "ie")
            customData.BrowserInfo = " Did you learn to program IE 8.0";
        else if (Browser == "firefox")
            customData.BrowserInfo = " Mozilla rocks, try Firebug & Fiddler addon's";
        else
            customData.BrowserInfo = " I did not test in this browser";
        return customData;
    }


Step 2:

Invoke the WCF service on the button click event, Make sure you set the expected data type as XML

function CountryProvinceWCFJSONMulti() {
            var browser = "";
            if (jQuery.browser.mozilla == true) browser="firefox"
            else if(jQuery.browser.msie == true) browser = "ie"
            varType                = "POST";
            varUrl                   = "service/CountryProvinceWCFService.svc/GetProvinceAndBrowser";
            //We are passing multiple paramers to the service in json format {"Country" : "india", "Browser":"ie"}
            varData                = '{"Country": "' + $('#ddlCountry').val() + '","Browser": "' + browser + '"}';
            varContentType   = "application/json; charset=utf-8";
            varDataType        = "json";varProcessData = true; CallService();
    }

Step 3:

On successful service invocation "ServiceSucceeded" will be called and the province value will get added to province drop down.

 function ServiceSucceeded(result) {
                    var ProvinceDDL = document.getElementById("ddlProvince");
                    for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }                   
                   //WCF Service with multiple output paramaetrs //First object 
                    var resultObject = result.GetProvinceAndBrowserResult.ProvinceInfo;
                    for (i = 0; i < resultObject.length; i++) {
                        var opt = document.createElement("option"); opt.text = resultObject[i];
                        ProvinceDDL.options.add(opt)
                    }
                    //Second object sent in JSON format
                    $("#divMulti").html(result.GetProvinceAndBrowserResult.BrowserInfo);          
                }

5. Calling WCF service using jQuery[ Get Method] and retrieving data in JSON Format

This time we will use GET Verb instead of POST to retrieve the data through WCF & jQuery

Step 1:

We can use the WebGet attribute instead of WebInvoke to perform the operation,
[OperationContract]
[WebGet(ResponseFormat=WebMessageFormat.Json)]
string[] GetProvinceGET(string Country);

Implement the contract

public string[] GetProvinceGET(string Country)
{return new CountryProvinceBL().GetProvince(Country);}

And use the web.config defined in figure 1

Step 2:

Set the verb to GET instead of POST and pass the data as a query string. Invoke the WCF Service using below method

function CountryProvinceWCFJSONGet() {
            varType                 = "GET";
            varUrl                    = "service/CountryProvinceWCFService.svc/GetProvinceGET?Country=" +$('#ddlCountry').val();
            varContentType    = "application/json; charset=utf-8";
            varDataType = "json";varProcessData = false; CallService();
        }

On successful service invocation "ServiceSucceeded" will be called and the province value will get added to province drop down.

function ServiceSucceeded(result) {
           var ProvinceDDL = document.getElementById("ddlProvince");
           for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }          
           for (i = 0; i < result.length; i++) {
               var opt = document.createElement("option"); opt.text = result[i];
               ProvinceDDL.options.add(opt)
           }
       }

6. Calling REST based WCF service using jQuery

Step 1:


Define the URI for REST service in the operation contract and set the BodyStyle to Bare.


[OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetProvinceREST/{Country}", BodyStyle=WebMessageBodyStyle.Bare)]
    string[] GetProvinceREST(string Country);

Implement the contract:

    public string[] GetProvinceREST(string Country)
    { return new CountryProvinceBL().GetProvince(Country);  }

Use the web.config defined in Figure 1

Step 2:

While using REST services use GET verb for retrieving data and POST , PUT , DELETE for modifying, adding and deleting information

function CountryProvinceWCFREST() {
            varType               = "GET";
            varUrl                  = "service/CountryProvinceWCFService.svc/GetProvinceREST/" + $('#ddlCountry').val();            
            varContentType  = "application/json; charset=utf-8";
            varDataType       = "json"; varProcessData = false; CallService();
        }

On successful service invocation "ServiceSucceeded" will be called and the province value will get added to province drop down.

function ServiceSucceeded(result) {
           var ProvinceDDL = document.getElementById("ddlProvince");
           for (j = ProvinceDDL.options.length - 1; j >= 0; j--) { ProvinceDDL.remove(j); }          
           for (i = 0; i < result.length; i++) {
               var opt = document.createElement("option"); opt.text = result[i];
               ProvinceDDL.options.add(opt)
           }
       }

Step 1:

Define the contract and set the return type to Stream since we are going to send it in Image/jpeg Format
[OperationContract]
[WebInvoke(Method = "GET")]
Stream GetPicture();

Implement the contract

public Stream GetPicture()
{
string fileName = Path.Combine(HostingEnvironment.ApplicationPhysicalPath,"vista.jpg");
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
// Set the content type as image/ jpeg
System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
return (Stream)fileStream;
}

And use the web.config which we defined earlier in this article

Step 2:

On Button click event set the src attribute of image element [image1] to the WCF service

function ShowImage() {// Call the WCF service
$("#image1").attr('src','service/CountryProvinceWCFService.svc/GetPicture');

}

| 0 comments ]


A tag cloud is a way to display a weighted list such that the weight of each item is reflected by the size of the item's text. Tag clouds provide a quick way for one to eyeball a list and ascertain what items are more prevalent. Oftentimes, each item in a tag cloud is rendered as a link that, when clicked, allows the user to drill into the selected category.

Ideally, a tag cloud could be associated with some data, a few properties set, and, voila, the tag cloud appears! In fact, we'll examine how to accomplish exactly this in a future article by creating a custom, compiled ASP.NET 2.0 server control. For now, though, let's just implement the tag cloud directly from an ASP.NET page (although this could be moved to a User Control for greater reuse opportunities).
First things first - we need the data that returns the list with each item weighted. In the demo downloadable at the end of this article, I have used a SqlDataSource control to query the Northwind database, returning the CategoryID, CategoryName, and number of products belonging to each category:

SELECT Categories.CategoryID, Categories.CategoryName, 
       COUNT(Products.ProductID) AS NumberOfProducts 

FROM Categories 
    INNER JOIN Products ON 
        Categories.CategoryID = Products.CategoryID 

GROUP BY Categories.CategoryID, Categories.CategoryName
ORDER BY Categories.CategoryName


This query uses the GROUP BY clause to return the count of products associated with each category. See Using the GROUP BY Clause for more information on this SQL clause.

The tag cloud is outputted in the Web page via a Literal Web control named CloudMarkup. In code we're going to loop through the database results, compute the font size scale, and then emit an HTML hyperlink as markup into the Text property of the Literal control. To start, we need to get the data from the SqlDataSource control. This is accomplished by calling its Select() method, which returns a DataView object:


'First, read data from SqlDataSource
Dim cloudData As DataView = CType(CategoriesProductsBreakdownDataSource.Select(DataSourceSelectArguments.Empty), DataView)

Next, a series of constants are defined in an attempt to generalize this code at least a little bit. For example, there are constants that define the names of the database columns that return the weight, the text field to display, along with the field to use (and a format string) when constructing the URL for each hyperlink. You'll also find the set of font sizes and the markup to inject between each link.


Const SpacerMarkup As String = " " 'The markup injected between each item in the cloud
Dim FontScale() As String = {"xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large"}

'All database column names are centralized here. To customize this, simply modify the column names here
Const WeightColumnName As String = "NumberOfProducts"
Const TextColumnName As String = "CategoryName"
Const NavigateUrlColumnName As String = "CategoryID"
Const NavigateUrlFormatString As String = "~/ViewProductsByCategory.aspx?CategoryID={0}"
Next, we need to determine the minimum and maximum weight values in the list. This information is then used to compute the linear scale by which we'll map an item's weight to a font size. The scaleUnitLength holds the "length" of each notch on the scale.

Dim minWeight As Decimal = Decimal.MaxValue, maxWeight As Decimal = Decimal.MinValue

For Each row As DataRowView In cloudData
    Dim numProductsObj As Object = row(WeightColumnName)
    If Not Convert.IsDBNull(numProductsObj) Then
       Dim numProductsDec As Decimal = Convert.ToDecimal(numProductsObj)

       If numProductsDec < minWeight Then minWeight = numProductsDec
       If numProductsDec > maxWeight Then maxWeight = numProductsDec
    End If
Next

Dim scaleUnitLength As Decimal = (maxWeight - minWeight + 1) / Convert.ToDecimal(FontScale.Length)

After computing the scale, the data is enumerated one more time, this time with a hyperlink element emitted for each record. To find the place on the scale, the current item's weight is subtracted from the minimum and divided by scaleUnitLength. This index is used to select the appropriate font size from FontScale. Also note that the specified values for NavigateUrlColumnName and NavigateUrlFormatString are used to configure the href portion of the hyperlink.

For Each row As DataRowView In cloudData
    Dim numProductsObj As Object = row("NumberOfProducts")
    If Not Convert.IsDBNull(numProductsObj) Then
       Dim numProductsDec As Decimal = Convert.ToDecimal(numProductsObj)

       Dim scaleValue As Integer = Math.Truncate((numProductsDec - minWeight) / scaleUnitLength)
       CloudMarkup.Text &= String.Format("<a href=""{0}"" style=""font-size:{1};"">{2}</a>{3}", _
                                    Page.ResolveUrl(String.Format(NavigateUrlFormatString, row(NavigateUrlColumnName).ToString())), _
                                    FontScale(scaleValue), row(TextColumnName).ToString(), SpacerMarkup)
    End If
Next

That's all there is to it! The resulting output is a chunk of HTML that, when rendered in the user's browser, lists each category as a hyperlink pointing to ViewProductsByCategory.aspx?CategoryID=categoryID. Each link's text size is based on its weight using a linear scale. The following screenshot below shows a tag cloud of the Northwind database's categories table along with the raw data used to populate the cloud.

| 0 comments ]

What does a CDN provide?

Content delivery networks (CDNs) are composed of "edge cache" servers that are strategically placed around the world at key Internet network points. These "edge cache" servers can be used to cache and deliver all types of content – including images, videos, CSS and JavaScript files.

Using a CDN can significantly improve a website's end-user performance, since it enables browsers to more quickly retrieve and download content. For example, instead of having a browser request for an image traverse all the way across the Internet to your web server to download, a CDN can instead serve the request directly from a nearby "edge cache" server that might only be a single network hop away from your customer (making it return much faster – which makes your pages load quicker).

What does the Microsoft AJAX CDN provide?

The Microsoft AJAX CDN makes it really easy to add the jQuery and ASP.NET AJAX script libraries to your web sites, and have them be automatically served from one of our thousands of geo-located edge-cache servers around the world.

For example, if you want to use jQuery from the Microsoft AJAX CDN then you can simply add a standard script tag to your page using the URL below:


   <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js" type="text/javascript">script>    


When the browser requests the script file it will be automatically served by the CDN "edge cache" server that is closest to the end-user. This means:

* The request will be processed much faster than if it had to hit your web-server (making the end-user's page load much faster)

* You don't have to pay for the bandwidth of this file – since the file comes from our server we pay the bandwidth cost (saving you money)

* The script can be easily cached across multiple web-sites – which means it might not even need to be downloaded if the user has already hit a web-site that requested the file (and as such has it already in the browser's cache).

You can get a full listing of the JavaScript libraries (and associated URLs) we already have loaded in our CDN cache here: www.asp.net/ajax/cdn

We'll update the available libraries in the CDN as we ship new versions of ASP.NET AJAX, and continue to update it to include all of the JavaScript files we ship with ASP.NET and Visual Studio (including jQuery, the jQuery Validation plugin, and additional libraries we ship in the future).

The CDN service is free and available for anyone in the community to use for both commercial and non-commercial purposes. You do not need to register to take advantage of it.
Using the Microsoft AJAX CDN with the ASP.NET 4.0 ScriptManager

In addition to allowing you to reference script files directly using a


<script src="http://ajax.microsoft.com/ajax/beta/0909/MicrosoftAjax.js" type="text/javascript">script>
    <script src="http://ajax.microsoft.com/ajax/beta/0909/MicrosoftAjaxTemplates.js" type="text/javascript">script>

| 1 comments ]

This article demonstrates how to use the jQuery UI AutoComplete widget to consume an ASP.NET Web Service (EmployeeList.asmx) that is JSON Serialized. The data source for this web service is List in the Employee.cs class. You can download this class from the source code attached with this article.
The Autocomplete widget is one of the widgets provided in jQuery UI and provides suggestions while you type into the field. jQuery UI is a free widget and interaction library built on top of the jQuery JavaScript Library, that you can use to build highly interactive web applications.

Let us first glance through the entire code with the jQuery UI AutoComplete widget added to the TextBox (tb)


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script> 
<script type="text/javascript">
$(function() {
    $(".tb").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "EmployeeList.asmx/FetchEmailList",
                data: "{ 'mail': '" + request.term + "' }",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataFilter: function(data) { return data; },
                success: function(data) {
                    response($.map(data.d, function(item) {
                        return {
                            value: item.Email
                        }
                    }))
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                }
            });
        },
        minLength: 2
    });
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
    <label for="tbAuto">Enter Email: </label>
     <asp:TextBox ID="tbAuto" class="tb" runat="server">
     </asp:TextBox>
</div>
</div>
</form>
</body>
</html>

Now before explaining to you how this code functions, let us go through the WebService first. Assuming you have downloaded the source code and are looking at the EmployeeList.cs/vb file, you will observe that the method has been decorated with the [WebMethod] attribute to allow calls from client script


<WebMethod>
Public Function FetchEmailList(ByVal mail As String) As List(Of Employee)
      Dim emp = New Employee()
      Dim fetchEmail = emp.GetEmployeeList().Where(Function(m) m.Email.ToLower().StartsWith(mail.ToLower()))
      Return fetchEmail.ToList()
End Function

Here the FetchEmailList(string mail) method calls the GetEmployeeList() method on the Employee class which returns a List. We then filter the list using the filter string (mail) passed from the UI and then return the list of emails that match the filter string.
Note: If a method is not marked with [ScriptMethod] attribute, the method will be called by using the HTTP POST command and the response will be serialized as JSON.
Going back to code we saw above, observe how the TextBox is wired to the AutoComplete widget.



$(function() {
    $(".tb").autocomplete({
        source: function(request, response) {
            $.ajax({
                // consume the webservice
        },
        minLength: 2
    });
});

To consume this web service using jQuery $.ajax(), two important points to note is that the request should be a POST request and the request’s content-type must be ‘application/json; charset=utf-8’. The code structure of the $.ajax() call looks similar to the following:


$.ajax({
    url: "EmployeeList.asmx/FetchEmailList",
    data: "{ 'mail': '" + request.term + "' }",
    dataType: "json",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    success: function(data) {
 
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
});

Observe how the parameter (that the user types in the textbox) is passed to the webservice using data: "{ 'mail': '" + request.term + "' }" .You may need to add additional checks to format the data or validate it. Once the Ajax method is completed, the success function will be executed and the matching results (Email) will be returned using the following code.


dataFilter: function(data) { return data; },
success: function(data) {
    response($.map(data.d, function(item) {
        return {
            value: item.Email
        }
    }))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
    alert(textStatus);
}

Now when you browse the page and type the first 2 characters in the textbox, the jQuery UI AutoComplete widget added to the TextBox, provides suggestion that it pulls from the JSON enabled WebService as shown below







| 0 comments ]

In this article, we will see how to read and filter the RSS Feed of codetechblog.blogspot.com using LINQ to XML. We will first read the RSS feed and populate the DropDownList with ‘Authors’ retrieved from the feed. We will then filter the feed results based on the Author selected in the DropDownList.
e will be reading and filtering the RSS feed of this site codetechblog.blogspot.com. The RSS feed can be obtained over here http://feeds.feedburner.com/codetechblog. Let us quickly jump to the solution.

Step 1: Create a new website (Open Visual Studio > File > New Website) called ‘FilterRSS.
Step 2: Drag and drop a GridView and a DropDownList control to the page.
Step 3: Once you visit the RSS Feed over here, right click on the page and View Source. You will find an XML file, since RSS is an XML file.
Let us now write a LINQ to XML query to read the Title, Link, Description and Author elements from our RSS Feed and filter the results. Add the following markup to the DropDownList and some template Columns to the GridView, to display content:

<div>
    <asp:DropDownList ID="DropDownList1" runat="server"
        onselectedindexchanged="DropDownList1_SelectedIndexChanged"
        AutoPostBack="True">
    </asp:DropDownList>
    <br /><br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:TemplateField HeaderText="Title">
         <ItemTemplate>
         <a href='<%# Eval("link") %>' target="_blank"><%# Eval("title") %></a>
         </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="Author"
           HeaderText="Author" />
       <asp:BoundField DataField="description" HtmlEncode="false"
               HeaderText="Description" />
    </Columns>
    </asp:GridView>
</div>

Step 4: Now create an ArticlesList class which will act as a container for the items read from the feed
VB.NET
Public Class ArticlesList
      Private privateTitle As String
      Public Property Title() As String
            Get
                  Return privateTitle
            End Get
            Set(ByVal value As String)
                  privateTitle = value
            End Set
      End Property
      Private privateLink As String
      Public Property Link() As String
            Get
                  Return privateLink
            End Get
            Set(ByVal value As String)
                  privateLink = value
            End Set
      End Property
      Private privateDescription As String
      Public Property Description() As String
            Get
                  Return privateDescription
            End Get
            Set(ByVal value As String)
                  privateDescription = value
            End Set
      End Property
      Private privateAuthor As String
      Public Property Author() As String
            Get
                  Return privateAuthor
            End Get
            Set(ByVal value As String)
                  privateAuthor = value
            End Set
      End Property
End Class

We are using Generics to return a strongly typed collection of IEnumerable items. This collection can now be passed to any other part of the application or stored in a session object to be used during postbacks.
The code will look similar to the following:

VB.NET
 
Imports System
Imports System.Linq
Imports System.Xml.Linq
Imports System.Collections.Generic
 
Partial Public Class _Default
      Inherits System.Web.UI.Page
      Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            If (Not IsPostBack) Then
                  Dim xFeed As XElement = XElement.Load("http://feeds.feedburner.com/netCurryRecentArticles")
 
                  Dim items As IEnumerable(Of ArticlesList) = From item In xFeed.Elements("channel").Elements("item") _
                                                              Select New ArticlesList
                                    item.Element("description").Value, Author = item.Element("author").Value
                                    item.Element("link").Value, Description = item.Element("description").Value, Author
                                    item.Element("title").Value, Link = item.Element("link").Value, Description
                                    Title = item.Element("title").Value, Link
 
                  'store items in a session
                  Session("feed") = items
 
                  Dim authors = items.Select(Function(p) p.Author).Distinct()
 
                  DropDownList1.DataSource = authors
                  DropDownList1.DataBind()
                  Dim selAuth As String = DropDownList1.SelectedValue
                  PopulateGrid(selAuth)
            End If
      End Sub
 
      Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
            Dim selAuth As String = DropDownList1.SelectedValue
            PopulateGrid(selAuth)
      End Sub
 
      Protected Sub PopulateGrid(ByVal author As String)
            Dim items = CType(Session("feed"), IEnumerable(Of ArticlesList))
 
            If items IsNot Nothing Then
                  Dim filteredList = From p In items _
                                     Where p.Author = author _
                                     Select p
 
                  GridView1.DataSource = filteredList
                  GridView1.DataBind()
            End If
      End Sub
End Class
In the code above, we load the Xml from the RSS feed using the XElement class. We then enumerate through all the Channel\Item elements and populate the items collection. This collection is stored in a Session object to be reused during postbacks.
Note: Observe the !IsPostBack which populates the collection only once, thereby saving the list from getting populated on every pageload.
We then apply a filter on this collection and select distinct authors and bind the result to a DropDownList. The selected author is passed to the PopulateGrid() method where the session object is casted back to IEnumerable. The list is then filtered based on the author passed and the results are bound to a GridView.
Similarly as and when the users selects a new author from the DropDownList, the list gets filtered and only the articles belonging to that author is displayed. Here are some screenshots:




I hope this article was useful and I thank you for viewing it

| 0 comments ]

This short article demonstrates how to rotate a group of Hyperlink Controls in the same position using jQuery.
Note that for demonstration purposes, I have included jQuery code in the same page. Ideally, these resources should be created in separate folders for maintainability.
People who have been monetizing their sites need no introduction to TextLinkAds. In simple words, Text Link Ads are Hyperlinks sponsored by Advertisers. When a user clicks on these hyperlinks, they are sent to the sponsor’s website. In this recipe, I will demonstrate how to rotate multiple hyperlinks or TextLinkAds on the same position.
Let us quickly jump to the solution and see how we can rotate a group of Hyperlink Controls using client-side code. This example uses the latest minified version of jQuery which is 1.3.2 that can be downloaded from here. This example assumes that you have a folder called "Scripts" with the jQuery file (jquery-1.3.2.min.js) in that folder

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Timer based toggling of hyperlink</title>
    <script type='text/javascript'
        src='../Scripts/jquery-1.3.2.min.js'>
    </script>
   
    <script type="text/javascript">
        $(function() {
            var anch = $("a.dev");
            $(anch).hide().eq(0).show();
            var cnt = anch.length;
 
            setInterval(linkRotate, 3000);
 
            function linkRotate() {
               $(anch).eq((anch.length++) % cnt).fadeOut("slow", function() {
                    $(anch).eq((anch.length) % cnt)
                    .fadeIn("slow");
                });
            }
        });
    </script>
 
</head>
<body>
    <form id="form1" runat="server">
    <div class="tableDiv">
        <h2>The Hyperlink and Text shown below changes after 3 seconds
        </h2><br />
        <asp:HyperLink ID="linkA" runat="server" class="dev"
            NavigateUrl="http://www.google.com">
            Google</asp:HyperLink>
        <asp:HyperLink ID="linkB" runat="server" class="dev"
            NavigateUrl="http://www.yahoo.com">
            Yahoo</asp:HyperLink>
        <asp:HyperLink ID="linkC" runat="server" class="dev"
            NavigateUrl="http://www.microsoft.com">
            Microsoft</asp:HyperLink>
    </div>
    </form>
</body>
</html>
We begin by hiding all the hyperlinks with class="dev" and then display the first one.

var anch = $("a.dev");
$(anch).hide().eq(0).show();
We then use the JavaScript setInterval() function to delay the execution of a function (linkRotate) for a specific time, in our case 3000 millisecond (3 seconds), as shown below:
setInterval(linkRotate, 3000);
The advantage of the setInterval() function is that it continues to repeat the process of triggering the function at the specified interval, thereby giving it a loop effect.
In the linkRotate() function, we use a simple expression (anch.length++) % cnt that calculates the index to be supplied to the eq() selector and applies the fadeout/fadeIn() animations on the current hyperlink. eq(0) refers to the first link, eq(1) to the second link and so on.
function linkRotate() {
    $(anch).eq((anch.length++) % cnt).fadeOut("slow"function() {
        $(anch).eq((anch.length) % cnt)
        .fadeIn("slow");
    });
}

| 0 comments ]

This short article demonstrates how to click and view a larger image when the thumbnail is clicked on.Note that for demonstration purposes, I have included jQuery and CSS code in the same page. Ideally, these resources should be created in separate folders for maintainability.

Let us quickly jump to the solution and see how we can view a larger image when an image is clicked on

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Click and Increase the Size of an Image</title>
    <style type="text/css">
        .imgthumb
        {
            height:100px;
            width:100px;
        }
        .imgdiv
        {
            background-color:White;
            margin-left:auto;
            margin-right:auto;
            padding:10px;
            border:solid 1px #c6cfe1;
            height:500px;
            width:450px;
        }
    </style>
    <script type="text/javascript"
     src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
    </script>
   
     <script type="text/javascript">
         $(function() {
             $("img.imgthumb").click(function(e) {
                 var newImg = '<img src='
                                + $(this).attr("src") + '></img>';
                 $('#ladiv')
                    .html($(newImg)
                    .animate({ height: '300', width: '450' }, 1500));
             });
         });    
     </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="imgdiv">
        <h2>Click on the thumbnail to view a large image</h2>
        <br />
        <asp:Image ID="imgA" class="imgthumb" runat="server"
            ImageUrl="../images/1.jpg" />
        <asp:Image ID="imgB" class="imgthumb" runat="server"
            ImageUrl="../images/2.jpg" />
        <asp:Image ID="imgC" class="imgthumb" runat="server"
            ImageUrl="../images/3.jpg" />
        <asp:Image ID="Image1" class="imgthumb" runat="server"
            ImageUrl="../images/4.jpg" />
        <hr /><br />
        <div id="ladiv"></div>
    </div>
    </form>
</body>
</html>
This recipe demonstrates how to increase the size of an image when it is clicked. To give it an Image gallery effect, when a thumbnail is clicked, we create a new image element and set its source, to the source of the clicked thumbnail.
var newImg = '<img src='
              + $(this).attr("src") + '></img>';
The next and final step is to set the html contents of a div element to the ‘newImg’ variable and then increase the image size, by animating the height and width of the image.
$('#ladiv')
         .html($(newImg)
         .animate({ height: '300', width: '450' }, 1500));
When you run the application, click on the thumbnail to see a large version of the image with animation, as shown below. Additionally, you can also preload the images for better performance..























I hope you found this article useful and I thank you for viewing it.

| 0 comments ]

This short article demonstrates how to change the opacity of an image when the user hovers the mouse over an image.
Note that for demonstration purposes, I have included jQuery and CSS code in the same page. Ideally, these resources should be created in separate folders for maintainability.
Let us quickly jump to the solution and see how we can change the opacity of an image.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Change Image Opacity on Hover</title>
    <style type="text/css">
    .imgOpa
    {
        height:250px;
        width:250px;
        opacity:0.3;
        filter:alpha(opacity=30);
    }
    </style>
    <script type="text/javascript"
     src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
    </script>
   
    <script type="text/javascript">
        $(function() {
            $('.imgOpa').each(function() {
                $(this).hover(
                    function() {
                        $(this).stop().animate({ opacity: 1.0 }, 800);
                    },
                   function() {
                       $(this).stop().animate({ opacity: 0.3 }, 800);
                   })
                });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>Hover over an Image to change its Transparency level</h2>
        <br />
        <asp:Image ID="Image1" runat="server"
            ImageUrl="../images/1.jpg" class="imgOpa" />
        <asp:Image ID="Image2" runat="server"
            ImageUrl="../images/2.jpg" class="imgOpa" />
        <asp:Image ID="Image3" runat="server"
            ImageUrl="../images/3.jpg" class="imgOpa" />
        <asp:Image ID="Image4" runat="server"
            ImageUrl="../images/4.jpg" class="imgOpa" />
    </div>
    </form>
</body>
</html>
In this example, observe that the images have a class attribute ‘imgOpa’. The definition of the CSS class is as shown here:
.imgOpa
    {
        height:250px;
        width:250px;
        opacity:0.3;
        filter:alpha(opacity=30);
    }
When the images are loaded, they are in a semitransparent state. In Firefox, Chrome and Safari, we use the opacity:n property for transparency. The opacity value can be from 0.0 - 1.0, where a lower value makes the element more transparent.
In IE 7 and later, we use filter:alpha(opacity=n) property for transparency, where the opacity value can be from 0-100.
When the user hovers the mouse over a semitransparent image, we use the jQuery hover() method to animate the opacity property from 0.3 to 1.0, thereby creating a cool effect on the images. The code to achieve this effect is shown below:
$(this).hover(
    function() {
        $(this).stop().animate({ opacity: 1.0 }, 800);
    },
   function() {
       $(this).stop().animate({ opacity: 0.3 }, 800);
   })
});
I hope you found this article useful and I thank you for viewing it

| 0 comments ]

This short article demonstrates how to create a watermark effect on your TextBox and display instructions to users, without taking up screen space.
Note that for demonstration purposes, I have included jQuery code in the same page. Ideally, these resources should be created in separate folders for maintainability.
Let us quickly jump to the solution and see how we can create a watermark effect on your TextBox using client-side code.

<!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="Head1" runat="server">
    <title>TextBox WaterMark</title>
    <script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
    </script>  
   
    <style type="text/css">
    .water
    {
         font-family: Tahoma, Arial, sans-serif;
         color:gray;
    }
    </style>
   
    <script type="text/javascript">
        $(function() {
 
            $(".water").each(function() {
                $tb = $(this);
                if ($tb.val() != this.title) {
                    $tb.removeClass("water");
                }
            });
 
            $(".water").focus(function() {
                $tb = $(this);
                if ($tb.val() == this.title) {
                    $tb.val("");
                    $tb.removeClass("water");
                }
            });
 
            $(".water").blur(function() {
                $tb = $(this);
                if ($.trim($tb.val()) == "") {
                    $tb.val(this.title);
                    $tb.addClass("water");
                }
            });
        });       
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="smallDiv">
     <h2>TextBox Watermark Demonstration</h2>    <br />          
        <asp:TextBox ID="txtFNm" class="water" Text="Type your First Name"
        Tooltip="Type your First Name" runat="server"></asp:TextBox><br />
        <asp:TextBox ID="txtLNm" class="water" Text="Type your Last Name"
        Tooltip="Type your Last Name" runat="server"></asp:TextBox>
        <br /><br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
        <br /><br />
        Tip: Click on the TextBox to start typing. The watermark
        text disappears.
    </div>
    </form>
</body>
</html>
The code shown above adds the “watermark” behavior to controls marked with the ‘class=water’ attribute. When the user loads the page, a watermarked textbox displays a message to the user. As soon as the watermarked textbox receives focus and the user types some text, the watermark goes away. This technique is a great space saver as you can use it to provide instructions to the user, without using extra controls that take up valuable space on your form.
The ‘Tooltip’ attribute applied to the textbox is crucial to this example. The ‘Tooltip’ gets rendered as ‘title’. Observe the code, as we use this ‘title’ property to compare it to the textbox value and remove the watermark css, when the textbox control gains focus
$(".water").focus(function() {
                $tb = $(this);
                if ($tb.val() == this.title) {
                    $tb.val("");
                    $tb.removeClass("water");
                }
            });
Similarly when the user moves focus to a different control without entering a value in the textbox, we add the watermark css again.

$(".water").blur(function() {
                $tb = $(this);
                if ($.trim($tb.val()) == "") {
                    $tb.val(this.title);
                    $tb.addClass("water");
                }
            });
The water class declared in Demos.css looks like this:
.water
{
     font-family: Tahoma, Arial, sans-serif;
     font-size:75%;
     color:gray;
}
When the user enters the First/Last Name and submits the form, the watermark behavior is no more needed to be displayed. This is achieved by comparing the ‘title’ with the ‘value’ of the textbox. If the ‘value’ does not match the ‘title’, this indicates that the user has entered some value in the textboxes and submitted the form. So in this case we remove the watermark appearance.
$(".water").each(function() {
                $tb = $(this);
                if ($tb.val() != this.title) {
                    $tb.removeClass("water");
                }
            });

| 0 comments ]

In this post I’ll show how to use jQuery to automatically convert all email addesses from static text into a mailto link.
Consider the following table which contains a person’s details including their email address.






Using jQuery I can easily find table cells that contain an email address by using a regular expression and then convert the address into a mailto link:
$().ready(function() {
    var regEx = /(\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)/;

    $("table td").filter(function() {
        return $(this).html().match(regEx);
    }).each(function() {
        $(this).html($(this).html().replace(regEx, "<a href=\"mailto:$1\">$1</a>"));
    });
});

First I’ve defined my email regular expression. I have also made sure the entire expression is in brackets, this sets up a regular expression group for the whole thing which I use when doing the replace.
For my example I’m only going to replace email addresses within a TD tag so my selector first gets these elements. I next use the filter function to only select the email address content from the TD by using the JavaScript match function with my email regular expression. I then iterate over the collection of elements and use the JavaScript replace function to replace the static email address with a mailto hyperlink to the same email address.
In my replace string I’m using $1, which will output the matching text from the original string from the first grouping in my regular expression. As I said earlier I put brackets around my entire regular expression so that the first grouping it the whole thing. This means that $1 will output the matched email address.
Now when I run my project the email addresses are automatically mailto links:

| 0 comments ]

This article demonstrates how to autoscroll a multiline textbox both upwards and downwards using jQuery 1.3.2.

Note that for demonstration purposes, I have included jQuery code in the same page. Ideally, these resources should be created in separate folders for maintainability. The code shown below has been tested on IE7, Firefox 3, Chrome 2 and Safari 4
Let us quickly jump to the solution and see how to AutoScroll a multiline textbox.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>AutoScroll a Multiline TextBox</title>
    <script type="text/javascript"
     src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
    </script>
 
   
    <script type="text/javascript">
        $(function() {
            var $tb = $('textarea[id$=tb1]');
 
            $('input[id$=btnScroll]').toggle(
            function(e) {
                e.preventDefault();
                scrollArea($tb, $tb[0].scrollHeight);
            },
            function(e) {
                e.preventDefault();
                scrollArea($tb, 0);
            });
        });
 
        function scrollArea(ctrl, ht) {
            ctrl.animate({ scrollTop: ht }, 1000);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="smallDiv">
        <h2>Scroll the box contents by clicking on the Button</h2>
        <br /><br />
        <asp:TextBox ID="tb1" runat="server" TextMode="MultiLine"
        Text="Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem
        Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
        Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
        Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
        Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum"
        Rows="5"/>
        <br />
        <asp:Button ID="btnScroll" runat="server" Text="Scroll"/>
        <br /><br />
        Tip: The Text can be scrolled both downwards and upwards.
    </div>
    </form>
</body>
</html>

When the user clicks on the button (btnScroll), we toggle the click behavior. On the first click, we cancel the postback by using e.preventDefault() and then call a function called scrollArea() passing in the textarea and the scrollHeight. The code $tb[0].scrollHeight is for scrolling downwards

e.preventDefault();
scrollArea($tb, $tb[0].scrollHeight);
When the user clicks the button (btnScroll) again, the postback is cancelled and the scrollHeight is set to 0 (zero). This is done for scrolling upwards.

e.preventDefault();
scrollArea($tb, 0);
The scrollArea() function accepts the textarea that is to be scrolled as well as the scrollHeight. We then animate the scrollTop property to scroll upwards/downwards depending on the height parameter. The duration of the animation is set to 1000 milliseconds which provides a smooth scrolling effect

function scrollArea(ctrl, ht) {
    ctrl.animate({ scrollTop: ht }, 1000);
}

The code here assumes that you are not scrolling the textarea manually and then clicking the Scroll button.
I hope you found this article useful and I thank you for viewing it.

| 1 comments ]

Recently a new version of jQuery was released. This version is 1.4. As with any new version, ultimately you see what used to take you several lines of code, now rolled up into a single line of code. I'm going to demonstrate a question I've been asked many times on forums and that is how to move selected items from one &lgt;select> element to another. I'll show you how you could do it using jQuery 1.3.2 and how to minimize the code by using the new 1.4 library. Before we begin, the new version can be found here.

The HTML
The HTML for this is pretty straight forward. It's simply two elements side by side with two buttons between them. Here's what it looks like:

<form method="get">             
      <select id="SelectLeft" multiple="multiple">
            <option value="1">Australia</option>
            <option value="2">New Zealand</option>
            <option value="3">Canada</option>
            <option value="4">USA</option>
            <option value="5">France</option>
      </select>
           
      <input id="MoveRight" type="button" value=" >> " />
      <input id="MoveLeft" type="button" value=" << " />
       
      <select id="SelectRight" multiple="multiple">          
      </select>
</form>














jQuery 1.3.2

Below is the code to move the selected items from each <select> element.
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>   
    <script language="javascript" type="text/javascript">
        $(function() {
            $("#MoveRight,#MoveLeft").click(function(event) {
                var id = $(event.target).attr("id");
                var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";
                var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";
 
                var selectedItems = $(selectFrom + "option:selected");
                var output = [];               
                $.each(selectedItems, function(key, e) {                   
                  output.push('<option value="' + e.value + '">' + e.text + '</option>');
                                });
               
                $(moveTo).append(output.join(""));               
                selectedItems.remove();
            });
        });
    </script>

I've bound one event handler for the button clicks. To decide which direction the selected items should go, I'm using the ID of the button that fired the event:

var id = $(event.target).attr("id");
var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";
var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";

Next I create an empty array and loop through every selected item and add it to the end of the array:

var output = [];               
$.each(selectedItems, function(key, e) {                   
      output.push('<option value="' + e.value + '">' + e.text + '</option>');
});

Then I append it to the end of the <select> element and remove the moved items:
$(moveTo).append(output.join(""));
selectedItems.remove();

Overall I think that's a good approach. In jQuery 1.4 we can make this better!

jQuery 1.4

In the new jQuery library, the team has introduced a new function called toArray. This retrieves all the DOM elements contained in the jQuery set, as an array. So here's the code below:

<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
    <script language="javascript" type="text/javascript">
        $(function() {
            $("#MoveRight,#MoveLeft").click(function(event) {
                var id = $(event.target).attr("id");
                var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";
                var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";
 
                var selectedItems = $(selectFrom + " :selected").toArray();
                $(moveTo).append(selectedItems);
                selectedItems.remove;
            });
        });
    </script>  

The first thing you'll notice is the code has been reduced. Thanks to the toArray function, I have eliminated the need to loop through the selected items. Now they're returned as an array

var selectedItems = $(selectFrom + " :selected").toArray();

And to add them to the <select> element, I no longer need to use the join function, I simply append them: $(moveTo).append(selectedItems);
 Nice and simple!

| 1 comments ]

Repeater control is one of the light weight control when compared to the other databound controls. It provides more flexibility on the layout of data displayed and the control itself will not render any additional HTML like GridView and DataList control do. It only renders the HTML we specified in the template columns which makes it light weight when compared to other controls.

Repeater control as such will not provide edit/update functionalities for the data.

In this article, we will overcome this difficulty and provide an edit update feature similar to GridView control using the powerful jQuery library and Ajax.
Refer the below figure to understand better.







Steps
  • Open Visual Studio 2008, Click File >Website and choose ASP.Net Website.
  • Select a language of your choice. I have selected C#. You can name your website as per your need.
  • Drag a Repeater control from the data tab of the Visual Studio.
  • You can add a Sql server Express database in App_Data Folder and create a table called Employee with all the necessary fields. Enter some sample data to display in the Repeater control.
  • Specify the HeaderTemplate, ItemTemplate and FooterTemplate to display the employee data in tabular format. Bind the Repeater control from codebehind by fetching employee detail from the express database we have created in App_Data folder.
Refer the below code,
ASPX
<asp:Repeater ID="rpEmployee" runat="server">
    <HeaderTemplate>
    <table border="0" ID="tblEmployee">
        <tr id="Tr2" runat="server" style="">
            <th id="Th1">
            </th>
            <th id="Th2">
            EmpID</th>
            <th id="Th3">
            EmpName</th>
            <th id="Th4">
            Department</th>
            <th id="Th5">
            Age</th>
            <th id="Th6">
            Address</th>
       </tr>                   
    </HeaderTemplate>
    <ItemTemplate>
      <tr ID='<%# Eval("EmpID") %>'>
                    <td>                       
                        <input type="button" value="Edit"/>
                        <input type="button" value="Update" style="display:none" />
                        <input type="button" value="Cancel" style="display:none" />
                    </td>
                    <td>
                       <%# Eval("EmpID") %>
                    </td>
                    <td>
                        <%# Eval("EmpName") %>
                    </td>
                    <td>
                        <%# Eval("Department") %>
                    </td>
                    <td>
                        <%# Eval("Age") %>
                    </td>
                    <td>
                      <%# Eval("Address") %>
                    </td>
       </tr>   
    </ItemTemplate>
    <FooterTemplate>
    </table>
    </FooterTemplate>
    </asp:Repeater>

CodeBehind
protected void Page_Load(object sender, EventArgs e)
    {
            rpEmployee.DataSource = GetEmployee("Select * from Employee");
            rpEmployee.DataBind();
    }
    public DataTable GetEmployee(string query)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
        SqlDataAdapter ada = new SqlDataAdapter(query, con);
        DataTable dtEmp = new DataTable();
        ada.Fill(dtEmp);
        return dtEmp;
    }
Execute the page and you can see the employee details in tabular view with an edit button.

Next, we will make the Repeater control’s row editable similar to the inbuilt edit feature of GridView control using jQuery library.

Providing Edit Update Feature

When the user clicks the edit button, we will hide the edit button and enable update & cancel button for that row. Just like GridView control, we will also populate the table cell value of the editing row in a textbox control to edit. After editing the value and on clicking Update button, we call a page method called UpdateEmployee() to update the employee details in the database using the jQuery’s ajax() method.

First, we will develop our page method UpdateEmployee() in our codebehind to update the employee details that is passed to it from jQuery’s ajax method.

[WebMethod]
   public static string UpdateEmployee(string empid,string name,string dept,string age,string address)  
    { 
        string UpdateQuery = "UPDATE [Employee] SET [EmpName] = @name, [Department] =  @dept, [Age] = @age, [Address] = @address WHERE [EmpID] = @empid";
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
        con.Open();
        SqlCommand com = new SqlCommand(UpdateQuery, con);
        com.Parameters.Add("@name", SqlDbType.VarChar, 50).Value = name;
        com.Parameters.Add("@dept", SqlDbType.VarChar, 50).Value = dept;
        com.Parameters.Add("@age", SqlDbType.Int, 4).Value = age;
        com.Parameters.Add("@address", SqlDbType.VarChar, 50).Value = address;
        com.Parameters.Add("@empid", SqlDbType.Int, 4).Value = empid;       
        int n = com.ExecuteNonQuery();
        con.Close();
 
        return n.ToString();
    }


As we all know, a page method should be public static and should be decorated with WebMethod attribute. You need to include the System.Web.Services namespace for the WebMethod attribute to work. To know more about page methods and consuming it from jQuery, please read Using JQuery in ASP.Net AJAX Applications – Part 1.

Next, we will move to the client side part of our implementation where we can provide an editing option to the user. Refer the above FAQ’s to integrate jQuery library into our project.

The following jQuery code will help us to do the rest of our operations.

<script src="_scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script language="javascript">
        $(function() {
            $("#tblEmployee > tbody > tr ").each(function() {
                var TRID = $(this).attr("id");
                $(this).find("td:first > input[value=Edit]").click(function() {                   
                    ResetOtherRowEdit();
                    ChangeTableCellToTextbox(TRID);
                    $(this).hide();
                    return false;
                });
 
                $(this).find("td:first > input[value=Update]").click(function() {
                    UpdateRow(TRID);
                });
 
                $(this).find("td:first > input[value=Cancel]").click(function() {
                    CancelEdit(TRID);
                });
 
            });
        });
 
        function ChangeTableCellToTextbox(RowID) {
            $("#" + RowID + "> TD").filter(function() {
                if ($(this).find("INPUT").html() == null & !($(this).is(":nth-child(2)"))) {
                    return true;
                }
            }).each(function() {
                var TDvalue = $(this).html();               
                var replacevalue = "<input type=text value=\"" + TDvalue + "\"></input>";
                $(this).html(replacevalue);
            });
 
            $("#tblEmployee > tbody > tr[id="+ RowID +"] > td:first> input[value=Update]").show();
            $("#tblEmployee > tbody >  tr[id=" + RowID + "] > td:first> input[value=Cancel]").show();
        }
 
        function UpdateRow(RowID) {           
            var empid = $("#" + RowID + "> TD:nth-child(2)").html();
            var empname =$("#" + RowID + "> TD:nth-child(3) > input[type=text]").val();
            var dept = $("#" + RowID + "> TD:nth-child(4) > input[type=text]").val();
            var age = $("#" + RowID + "> TD:nth-child(5) > input[type=text]").val();
            var address =$("#" + RowID + "> TD:nth-child(6) > input[type=text]").val();
 
            var options = {
                type: "POST",
                url: "RepeaterEdit.aspx/UpdateEmployee",
                data: "{\"empid\":\"" + empid + "\",\"name\":\"" + empname + "\",\"dept\":\"" + dept + "\",\"age\":\"" + age + "\",\"address\":\"" + address + "\"}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    if (response.d != "") {
                        if (response.d == "1") {
                            alert("Updation Successful");
                            CancelEdit(RowID);
                        }
                        else {
                            alert("Updation failed!");
                        }
                    }
                }
            };
            //Call the PageMethods
            $.ajax(options);         
        }
 
        function CancelEdit(RowID) {
            $("#" + RowID + "> TD").filter(function() {
                if ($(this).find("INPUT[type=text]").val() != null) {
                    return true;
                }
            }).each(function() {              
                $(this).html($(this).find("INPUT[type=text]").val());
            });
          $("#tblEmployee > tbody > tr[id=" + RowID + "] > td:first> input[value=Update]").hide();
          $("#tblEmployee > tbody >  tr[id=" + RowID + "] > td:first> input[value=Cancel]").hide();
          $("#tblEmployee > tbody >  tr[id=" + RowID + "] > td:first> input[value=Edit]").show();
      }
 
      function ResetOtherRowEdit() {
          $("#tblEmployee > tbody > tr ").each(function() {
              var TRID = $(this).attr("id");
              if ($(this).find("td:first > input[value=Update]").css("display") == "inline") {
                  CancelEdit(TRID);
              }
          });
      }       
    </script>

Execute the page and see it in action.

The ajax() method uses JSON and POST method to send the employee data to the page method. Once the data is updated successful, the page method will return 1 which indicates success(No of rows affected in ExecuteNonQuery() in our case). On success, you will see a success alert message.

Things to consider

  • The above jQuery code will call the page method even if you have not changed the details in any cell. You can modify UpdateRow() method to call the page method only if the value is changed by comparing with initial table cell value.
  • The above jQuery code will change the table cell to textbox by populating its value to textbox directly. You can get the employee detail for that row using the employeeid from the server to get the latest data. You can write one more page method that can return the employee detail in JSON format and populate the textboxes.