Friday, March 25, 2011

Using jQuery with ASP.NET Master Page

jQuery has gained popularity as the de facto standard for JavaScript development and many ASP.NET developers have adopted jQuery as part of their development kits. One question that I am asked frequently is how to use jQuery with an ASP.NET Master Page. Where should the jQuery file and code be placed in a Master Page?

In this article, I am going to answer these questions and will demonstrate how to use jQuery with an ASP.NET MasterPage. We will see some jQuery code that clones the content of one TextBox into another TextBox.


Let’s get started.
Step 1: Create a Master Page (MasterPage.master) and add a reference to the jQuery Library. Now create a folder called ‘Scripts’ and download the latest jQuery library into this folder. Now add references to any CSS files, if any. Create a separate folder to store all CSS and images files. You should always make it a habit to keep your resources in separate folders for better maintainability. The code should look similar to the following:


Step 2: Now create a Content Page called ‘Default.aspx’ and add two TextBox controls to this page as shown below:
Step 3: Now in the ‘Scripts’ folder, create a textboxclone.js file and add the following code in it.
Using the code shown above, as the user types in the first TextBox, we retrieve the value of the first TextBox and set it to the value of the second TextBox. Note: Since we are capturing the keyup event, whenever the user pastes text in the first textbox using Ctrl+v, the contents are cloned into the second textbox, This is however not true when the user right clicks the textbox and chooses paste from the context menu
The last step is to reference this JavaScript file (textboxclone.js) in your Content Page as shown below:
You must be wondering why did we add a link to the textboxclone.js from a Content page rather than doing it from a Master Page. The reason is, if we had referenced the textboxclone.js file in the MasterPage directly, the code would be downloaded for every content page, even if it was not needed. Referencing it from a Content Page makes sure that the resource is used only when this content page is requested. That’s it. Run the code and you will see the textbox text cloning in action.
I hope you liked this article and I thank you for viewing it.

Paging in ASP.NET using jTemplate, jQuery & JSON

This article demonstrates how to apply paging in ASP.NET using jTemplate, jQuery and JSON. When working with a large dataset, it’s not a good idea to show all the records at once as it leads to performance issues in your website if a large number of visitors visit your site. Thus paging helps improve performance as the records are processed on demand.

Note: If you are not familiar with using jTemplate in ASP.NET, read this article
jTemplate, jQuery and JSON in ASP.NET before reading this one. Let’s start.

Step 1: Open VS 2010. Create a new ASP.NET project using File > Web Site. Give the website a name and press the OK button. In this website, I have created a Message and GridDataSet classes as shown below. 
public class Message
{
    public long ID { get; set; }
    public string Subject { get; set; }
    public String Body { get; set; }
    public DateTime Date { get; set; }
}
public class GridDataSet
{
    public int PageNumber { get; set; }
    public int TotalRecords { get; set; }
    public int PageSize { get; set; }
    public List<Message> MessageList { get; set; }
}
Step 2: I have created Messages() function which will return a list of Messages to the FetchData function. The FetchData function will return GridDataSet List.
using System.Web.Script.Serialization;
[WebMethod]
public static GridDataSet FetchData(int pageSize, int pageNumber)
{
    return new GridDataSet { PageNumber = pageNumber, TotalRecords = Messages().Count, PageSize = pageSize, MessageList = Messages().Skip(pageSize * pageNumber).Take(pageSize).ToList<Message>() };
}
public static List<Message> Messages()
{
    return new List<Message>()
    {
        new Message(){ ID=101, Subject="Aamir Hasan",Body="HI, How are you ",Date=DateTime.Now },
        new Message(){ ID=102, Subject="demo tutorial",Body="i have you visited",Date=DateTime.Now },
        new Message(){ ID=103, Subject="banner",Body="verfied",Date=DateTime.Now },
        new Message(){ ID=104, Subject="embed flash",Body="?",Date=DateTime.Now },
        new Message(){ ID=105, Subject="dotnetcurry.com",Body=".NET articles",Date=DateTime.Now },
        new Message(){ ID=106, Subject="Aamir Hasan",Body="done",Date=DateTime.Now },
        new Message(){ ID=107, Subject="asp.net",Body="asp.net..",Date=DateTime.Now },
        new Message(){ ID=108, Subject="Aamir Hasan 4",Body="...",Date=DateTime.Now },
        new Message(){ ID=109, Subject="Aamir Hasan 5",Body="...",Date=DateTime.Now },
        new Message(){ ID=1010, Subject="Aamir Hasan 6",Body="...",Date=DateTime.Now },
        new Message(){ ID=1011, Subject="Aamir Hasan 7",Body="...",Date=DateTime.Now },
        new Message(){ ID=1012, Subject="Aamir Hasan 8",Body="...",Date=DateTime.Now },
        new Message(){ ID=1013, Subject="Aamir Hasan 9",Body="...",Date=DateTime.Now }   
    };
}
Step 3: You can find the 'ForEachMessageTemplate.htm' file inside the jTemplate folder, which will used to render the html. I have also applied CSS on the table.

Step 4: Add the following code to Default.aspx page. On page load, the jQuery Ajax method will send the page size and page number to server side to retrieve the JSON Object.


 

<link href="Styles/Style.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.4.1.js" type="text/javascript">script>
<script src="http://github.com/malsup/corner/raw/master/jquery.corner.js?v2.09" type="text/javascript">script>
<script src="Scripts/jtemplates.js" type="text/javascript">script>
<script type="text/javascript">
    function Loader(isFade) {
        if (isFade) {
            $('#progressBackgroundFilter').fadeIn();
            $('#loadingbox').fadeIn();
            $('#Loader').fadeIn();
        } else {
            $('#progressBackgroundFilter').fadeOut();
            $('#loadingbox').fadeOut();
            $('#Loader').fadeOut();
        }
    }
    $(document).ready(function () {
        var pageSize = 5;
        var pageNumber = 0;
        getData(pageSize, pageNumber);
    });
    function getData(pageSize, pageNumber) {
        defaultParameters = "{pageSize:" + pageSize + ",pageNumber:" + pageNumber + "}";
        Loader(true);
        $.ajax({
            type: "POST",
            url: "Default.aspx/FetchData",
            data: defaultParameters,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: (function Success(data, status) {
                $('#placeholder').setTemplateURL('JTemplates/ForEachMessageTemplate.htm',
                                null, { filter_data: false });
                $('#placeholder').processTemplate(data.d)
                NoRecord(eval(data.d.MessageList));
                Loader(false);
                setPageNumber(pageSize);
            }),
            error: (function Error(request, status, error) {
                $("#placeholder").html(request.statusText).fadeIn(1000);
                Loader(false);
            })
        });
    }
    function NoRecord(e) {
        if (e == "")
        { $('#nofound').show(); }
        else
        { $('#nofound').hide(); }
    }
    function setPageNumber(pageSize) {
        $("#ddPaging").change(function (e) {
            var pageIndex = $(this).val() - 1;
            if (pageIndex != -1)
                getData(pageSize, pageIndex);
        });
    }
script>
 
You can see there are div elements as shown below to display records and also a loader which will be run before loading records and unload after retrieving records.
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h1>How to Apply Paging in Jtemplate in asp.net using,Linqh1>
    <p><div id="placeholder" style="clear: both;">div>p>
    <div id="Loader">
        <div id="loadingbox">
            <br/><br/><br/>
            processingdiv>
        <div id="progressBackgroundFilter">div>
    div>
asp:Content>
After running the code, the following output will be created.
Output


I have used firebug to comfim that only 5 records has been retrieved by jQuery Ajax method to the client side, as shown below.


Conclusion
Using paging in ASP.NET with jTemplate, jQuery and JSON makes your site perform better and faster, especially in situations when your site has a large number of visitors.

TextBox AutoComplete with ASP.NET and jQuery UI

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 jQuerytitle>
<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
C#
[WebMethod]
public List<Employee> FetchEmailList(string mail)
{
    var emp = new Employee();
    var fetchEmail = emp.GetEmployeeList()
    .Where(m => m.Email.ToLower().StartsWith(mail.ToLower()));
    return fetchEmail.ToList();
}
VB.NET
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
WebService
WebService_1
The entire source code of this article can be downloaded over here . I hope you liked the article and I thank you for viewing it.

What's New in ASP.NET 4.0 – SEO Enhancements with MetaKeywords and MetaDescription properties

 
With the ASP.NET 4.0 release round the corner, I thought of starting an article series that covers the new features introduced in ASP.NET 4.0, one at a time. This article is Part I of this multi-part series. In this article, we will take an overview of the two new properties added to the Page class in ASP.NET 4.0 – MetaKeywords and MetaDescription.
The MetaDescription is important from an SEO perspective. The META Description Tag is an integral part which identifies a page and irrespective of the contrary belief, I think search engines take this meta tag seriously. You should too!
Now in ASP.NET 2.0/3.5, you could use the HTMLMeta class to define HTML elements for your page as shown below:
HtmlMeta meta1 = new HtmlMeta();
meta1.Name = "keywords";
meta1.Content = "some keywords";
 
HtmlMeta meta2 = new HtmlMeta();
meta2.Name = "description";
meta2.Content = "add meta description";
 
Page.Header.Controls.Add(meta1);
Page.Header.Controls.Add(meta2);
Too much code!
However in ASP.NET 4.0, you now have two new properties added to the Page class – MetaKeywords and MetaDescription.
MetaDescription
So you can now declaratively define MetaKeywords and Description directly in your Page as shown below:
<%@ Page Title="New Features in ASP.NET 4" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
MetaKeywords="ASP.NET 4, SEO" MetaDescription="This page contains information about ASP.NET 4 and SEO enhancements" %>
 
 The markup gets rendered in the browser as:
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head><title>
New Features in ASP.NET 4
title><link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<meta name="description" content="This page contains information about ASP.NET 4 and SEO enhancements" />
<meta name="keywords" content="ASP.NET 4, SEO" />
head>
...
You can also programmatically define the MetaKeywords and MetaDescription properties by reading them from a database or manually declaring them on the Page object as shown here:
C#
protected void Page_Load(object sender, EventArgs e)
{
        Page.MetaDescription = "This page contains information about ASP.NET 4 and SEO enhancements";
        Page.MetaKeywords = "ASP.NET 4, SEO";
}
 
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      Page.MetaDescription = "This page contains information about ASP.NET 4 and SEO enhancements"
      Page.MetaKeywords = "ASP.NET 4, SEO"
End Sub
Note: If these meta tags are already declared on your page, then they will be overwritten when you follow the techniques shown above. For example, if your page already has existing meta tags..
<head runat="server">
    <title>title>
    <meta name="description" content="sample content" />
    <meta name="keywords" content="k1, k2" />
 
..and if you explicitly set the MetaDescription and MetaKeywords properties through the Page object, then these properties will overwrite the Meta tag contents already present on the page.
In order to retain the older meta tag contents and also use the new ones, just concatenate the two programmatically as shown below:
C#
protected void Page_Load(object sender, EventArgs e)
{
        Page.MetaDescription = Page.MetaDescription + " This page contains information about ASP.NET 4 and SEO enhancements";
        Page.MetaKeywords = Page.MetaKeywords + " ASP.NET 4, SEO";
}
 
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      Page.MetaDescription = Page.MetaDescription & " This page contains information about ASP.NET 4 and SEO enhancements"
      Page.MetaKeywords = Page.MetaKeywords & " ASP.NET 4, SEO"
End Sub
The Meta tags now get rendered in the browser as shown below, concatenating both the older and new values:
<head><title>
New Features in ASP.NET 4
title>
<meta name="description" content="sample content This page contains information about ASP.NET 4 and SEO enhancements" />
<meta name="keywords" content="k1, k2 ASP.NET 4, SEO" /><link href="Styles/Site.css" rel="stylesheet" type="text/css" />
head>
 
In the upcoming articles, we will continue exploring new features of ASP.NET 4.0. I hope you liked the article and I thank you for viewing it.

Popular Posts