Showing posts with label Asp.net MVC. Show all posts
Showing posts with label Asp.net MVC. Show all posts

Wednesday, 11 March 2015

ASP.NET MVC VERSIONS AND DIFFRENCES Or Diffrence Between ASP.NET MVC2 and MVC3 and MVC4 and MVC5

Microsoft ASP.NET MVC VERSIONS AND DIFFRENCES

MVC Release History
The Current Version of ASP.NET MVC is 4 and it was released on 15th Aug 2012. ASP.NET MVC is packaged with Visual Studio 2012 and MVC can be installed for Visual Studio 2010. Below We have mentioned the release history of ASP.NET MVC.
Date
Version
10 Dec 07
ASP.NET MVC CTP
13 Mar 09 
ASP.NET MVC 1.0
16 Dec 09
ASP.NET MVC 2 RC
04 Feb 10
ASP.NET MVC 2 RC 2
10 Mar 10
ASP.NET MVC 2
06 Oct 10
ASP.NET MVC 3 Beta
09 Nov 10
ASP.NET MVC 3 RC
10 Dec 10
ASP.NET MVC 3 RC 2
13 Jan 11
ASP.NET MVC 3
20 Sep 11
ASP.NET MVC 4 Developer Preview
15 Feb 12
ASP.NET MVC 4 Beta
31 May 12
ASP.NET MVC 4 RC
15 Aug 12
ASP.NET MVC 4
30 May 13
ASP.NET MVC 4 4.0.30506.0 
26 Jun 13
ASP.NET MVC 5 Preview
23 Aug 13
ASP.NET MVC 5 RC 1
17 Oct 13
ASP.NET MVC 5
17 Jan 14
ASP.NET MVC 5.1
10 Feb 14
ASP.NET MVC 5.1.1
4 Apr 14
ASP.NET MVC 5.1.2
27 May 14
ASP.NET MVC 5.2.0 Rc
01 Jul 14
ASP.NET MVC 5.2.0
23 Aug 14
ASP.NET MVC 5.2.2-Rc
Date
Version 
10 Dec 07
ASP.NET MVC CTP
13 Mar 09 
ASP.NET MVC 1.0
16 Dec 09
ASP.NET MVC 2 RC
In this ASP.NET MVC tutorial, we will have a quick look into new and important features introduced in major versions of Microsoft ASP.NET MVC starting from MVC 3 to MVC 5 (the latest one so far).
ASP.NET MVC 2
§  MVC2 uses only Web Forms View Engine(.aspx) as a default View Engine.
§  Chart, WebGrid , Crypto, WebImage, WebMail Contolrs not available
§  (HTML syntax) Web Forms View Engine synatax : <%=Html code %>
§  It’s Support only Master Pages only not Layout Pages.
ASP.NET MVC 3
§  New Project Templates having support for HTML 5 and CSS 3.
§  Improved Model validation.
§  Razor View Engine introduced with a bundle of new features.
§  Having support for Multiple View Engines i.e. Web Forms view engine, Razor or open source.
§  Controller improvements like ViewBag property and ActionResults Types etc.
§  Unobtrusive JavaScript approach.
§  Improved Dependency Injection with new IDependencyResolver.
§  Partial page output caching.
ASP.NET MVC 4
§  ASP.NET Web API, a framework that simplifies the creation of HTTP services and serving a wide range of clients. Follow to create your first ASP.NET Web API service.
§  Adaptive rendering and other look-n-feel improvements to Default Project Templates.
§  A truly Empty Project Template.
§  Based on jQuery Mobile, new Mobile Project Template introduced.
§  Support for adding controller to other project folders also.
§  Task Support for Asynchronous Controllers and Asynchronous Methods.
§  Controlling Bundling and Minification through web.config.
§  Support for OAuth and OpenID logins using DotNetOpenAuth library.
§  Support for Windows Azure SDK 1.6 and new releases.
§  Refreshed and modernized default project template.
§  Recipes to customize code generation.
§  In Razor view engine new features added like Condition attribute and ‘Tlide slash’ i.e URL Resolution.
ASP.NET MVC 5
§  Creating your first ASP.NET MVC 5 Application in 4 simple steps
§  Bootstrap replaced the default MVC template.
§  ASP.NET Identity for authentication and identity management.
§  Authentication Filters for authenticating user by custom or third-party authentication provider.
§  With the help of Filter overrides, we can now override filters on a method or controller.
§  Attribute Routing is now integrated into MVC 5.
ASP.NET MVC6 | ASP.NET vNext
§  Single Programming Model for ASP.NET MVC and ASP.NET Web API.
§  Optimized for Cloud Computing.
§  Supporting side by side deployment of runtime and framework along with application.
§  Out of the box support for dependency injection.
§  vNext is Open Source and supports running on multiple platforms including Linux and Mac.
§  New JSON-based project Extension.
§  In order to dynamically compile code, Roslyn compiler is used.
§  MVC 6 added new cloud computing optimization system of MVC , web API, SignalR and entity framework.
§  The Microsoft  make a bundle of MVC, Web API, WebPages, SignalR , That bundle we called MVC 6.
§  In MVC 6, Microsoft removed the dependency of system.web.dll from MVC 6  because it's so expensive. Typically  it consume 30K memory per request/response.
§  Right now, in MVC 6 consume 2K  memory per request response. It's too small memory  consume.
§  Most of the problem solved using the Roslyn Compiler.
§  The ASP .Net  vNext used the Roslyn Compiler,  By using Roslyn compiler do not need to compile the application Its  compile automatically the application code.
§  The .Net vNext is a cross platform and open source.
§  The .Net vNext has the new project extension project.json. Basically project.json contain the all dependency dll of the application.
§  In MVC 5.1 and 5.2 support to Enum and EnumHelper in  razor views.

Hopefully, this article will help you in comparing core features of ASP.NET MVC in different versions.

Monday, 11 August 2014

ViewData vs ViewBag vs TempData vs Session

Introduction

ViewData and ViewBag are used for the same purpose to transfer data from controller to view. Both life lies only in current request. ViewData is nothing but dictionary of object and it is accessible by string as key. ViewData is property of controller that exposes an instance of the ViewDataDictionary class. ViewBag is very similar to ViewData. ViewBag is a dynamic property (dynamic keyword which is introduced in .net framework 4.0). ViewBag is able to set and get value dynamically and able to add any number of additional fields without converts it to strongly typed. ViewBag is just a wrapper around the ViewData.

ViewData Example
//Controller Code
public ActionResult Index()
{
      List<string> Student = new List<string>();
      Student.Add("Vineet");
      Student.Add("Buddhi");
      Student.Add("Rakesh");

      ViewData["Student"] = Student;
      return View();
}
//page code
<ul>
@foreach (var student in ViewData["Student"] as List<string>)
{
@student
}
</ul>

ViewBag Example

//Controller Code
public ActionResult Index()
{
      List<string> Student = new List<string>();
      Student.Add("Vineet");
      Student.Add("Buddhi");
      Student.Add("Rakesh");

      ViewBag.Student = Student;
      return View();
//page code
<ul>
@foreach (var student in ViewData["Student"] as List<string>)
{
@student
}
</ul>

TempData is a dictionary which is derived from TempDataDictionary class. TempData is stored data just like live session for short time. TempData Keep data for the time of HTTP Request it mean that it hold data between two consecutive requests. TempData help us to transfer data between controllers or between actions. TempData internally use Session variables. Note that TempData is only work during the current and subsequent request. It is generally used to store one time message. With the help of TempData.Keep() method we can keep value in TempData object after request completion.

TempData Example
 
//Controller Code
public ActionResult Index()
{
    List<string> Student = new List<string>();
    Student.Add("Buddhi");
    Student.Add("Vineet");
    Student.Add("Rakesh");

    TempData["Student"] = Student;
    return View();
}
//page code
<ul>
@foreach (var student in ViewData["Student"] as List<string>)
{
@student
}
</ul>

ViewData VS ViewBag VS TempData
 
ViewData
ViewBag
TempData
It is Key-Value Dictionary collection
It is a type object
It is Key-Value Dictionary collection
ViewData is a dictionary object and it is property of ControllerBase class
ViewBag is Dynamic property of ControllerBase class.
TempData is a dictionary object and it is property of controllerBase class.
ViewData is Faster than ViewBag
ViewBag is slower than ViewData
NA
ViewData is introduced in MVC 1.0 and available in MVC 1.0 and above
ViewBag is introduced in MVC 3.0 and available in MVC 3.0 and above
TempData is also introduced in MVC1.0 and available in MVC 1.0 and above.
ViewData  is also work with .net framework 3.5 and above
ViewBag  is only  work with .net framework 4.0 and above
TempData  is also work with .net framework 3.5 and above
Type Conversion code is required while enumerating
In depth, ViewBag is used dynamic, so there is no need to type conversion while enumerating.
Type Conversion code is required while enumerating
It value become null if redirection is occurred.
Same as ViewData
TempData is used to pass data between two consecutive requests.
It lies only during the current request.
Same as ViewData
TempData is only work during the current and subsequent request

Wednesday, 1 January 2014

ASP.NET Web API in MVC tutorial

Introduction to ASP.NET Web API

ASP.NET Web API is one of new exciting feature of ASP.NET MVC 4. It is ideal framework for creating RESTful applications with .NET framework. It makes easy to build HTTP services and reach large number of clients like browsers and mobile devices. You can use XML or JSON or something else with these API.
ASP.NET Web API allows you create api or http based service or client endpoints. Although it comes with ASP.NET MVC4, it is much flexible framework to develop REST and AJAX API for HTML5, ASP.NET Web forms, client server desktop applications. Unlike WCF Web API does not required much configuration settings and you can host it in your own applications.

WCF or ASP.NET Web API

Below points can help you to choose WCF or ASP.NET Web API
  • If you want to create resource based services and need to take full advantage of HTTP like cache control for browsers, transfer different kind of content types like documents, images, HTML pages ASP.NET Web API should be selected.
  • If you have heterogeneous clients for same service and needs to call service using different protocols like netTCPBinding, netNamedPipeBinding, wsHttpBinding WCF is the obvious choice.
  • If you have special requirements like CallBackContract, One way communication or queuing then WCF should be selected.
In this article we will create a simple ASP.NET web api application in MVC. This application will read the data from Customers.xml file and show it on web page using jQuery.

Implementation of ASP.NET Web API in MVC

  1. Create new ASP.NET Web API

    Open visual studio and click on File -> New Project -> Select ASP.NET MVC4 Web Application
    Name the application as NorthwindWebApi
    From next window select Web API template and Razor as ViewEngine.
    New ASP.Net MVC4 Project
  2. Customer Model

    A Model manages properties and data of application and it contains all application logic like business logic, validation logic or data access logic. Model binders helps controller to keep its code cleanly separated from actual request and its environment.
    ASP.NET web api will produce serialized data of model to JSON, XML or some other format. It also writes HTTP Response messages with serialized data. Client can use GET verb to get data in specific format like JSON or XML by setting Accept header HTTP Request message.
    Create a new class in Model folder. Name it as Customer
    Customer Model will represent Customer entity from datastore. Add below properties to Model.
        namespace NorthwindWebApi.Models
        {
            public class Customer
            {
                public string CustomerID { get; set; }
                public string CompanyName { get; set; }
                public string City { get; set; }
            }
        }
                
  3. Customer ApiController

    The controllers in Web API inherits from ApiController class instead of Controller. The major difference between them is, actions from ApiController returns data and not Views. Add Customer ApiController by right click on Controllers folder from Solution Explorer. Select Add -> Controller. Name it as CustomerController
    From next window select Empty Api Controller.
    ASP.NET Web API controller
    Add below code to CustomerController. It has two methods GetAllCustomers which returns all the customers from Customer.xml and GetCustomer which takes id as input parameter and return its customer details.
    using NorthwindWebApi.Models;
    using System.Xml.Linq;
    using System.Collections;  
    
    namespace NorthwindWebApi.Controllers
    {
        public class CustomerController : ApiController
        {
            public List<customer> GetAllCustomers()
            {            
                List<Customer> customers = new List<Customer>();
                 
                XDocument doc = XDocument.Load("C:\\Customers.xml");
    
                foreach (XElement element in doc.Descendants("DocumentElement")
                    .Descendants("Customer"))
                {
                    Customer customer = new Customer();
    
                    customer.CustomerID = element.Element("CustomerID").Value;
                    customer.CompanyName = element.Element("CompanyName").Value;
                    customer.City  = element.Element ("City").Value;
    
                    customers.Add(customer);   
                }
    
                return customers;
            }
    
            public Customer GetCustomer(int id)
            {
                Customer customer = new Customer();
    
                XDocument doc = XDocument.Load("C:\\Customers.xml");
                
                XElement element = doc.Element("DocumentElement")
                                    .Elements("Customer").Elements("CustomerID").
                                    SingleOrDefault(x => x.Value == id.ToString());
                
                if (element != null)
                {
                    XElement parent = element.Parent;
    
                    customer.CustomerID =
                            parent.Element("CustomerID").Value;
                    customer.CompanyName =
                            parent.Element("CompanyName").Value;
                    customer.City =
                            parent.Element("City").Value;
    
                    return customer;
                }
                else
                {
                    throw new HttpResponseException
                        (new HttpResponseMessage(HttpStatusCode.NotFound));
                }
            }
        }
    }
                
  4. Customer View

    As Web API does not return View or ActionResult, for this tutorial you can use default Index.cshtml under Views -> Home folder.
    Replace html from Index.cshtml with below code which shows all customers by retrieving JSON through jQuery call to Customer Web API.
    <div id="body">
    <section class="content-wrapper main-content clear-fix">
        <div>
            <h2>All Customers</h2>
        </div>
        <div>
            <table id="customers" style="border: 1px solid black;"  ></table> 
        </div>
            
    </section>
    </div>
    
    @section scripts {
    <script>
    
        var apiCustomers = 'api/customer';
        $(document).ready(function () {
            // Send an AJAX request
            var rows = '';
            $('#customers').empty();
    
            $.getJSON(apiCustomers,
                function (data) {
                    $.each(data, function (key, val) {
                        var customerURL = apiCustomers + '/' + val.CustomerID;
                        rows = rows + '<tr style="border: 1px solid black;"><td>  ' +
                        '<a style="color: Blue; font-weight:bold; font-size:15px"'
                           + 'href="' + customerURL + '">' + val.CustomerID + '</a>' +
                            '</td><td>' + val.CompanyName + 
                            '</td><td>' + val.City + '</td></tr>';
                    });
                    $('#customers').html(rows);
                });
        });
    </script>
    }
                

    It shows all the customers and link to each customer.
    ASP.NET Web API All Customers

    Now click on CustomerID link to see Customer details.

    ASP.NET Web API Get Customer Details
    As we haven't implemented any HTML view for customer details it shows customer details in browser. Depending on your browser it shows the customer details Chrome and Firefox will show xml whereas Internet Explorer will show it in JSON. It is because the request attribute Accept-headers send by browsers are different.

Paging and sorting in ASP.NET MVC and Entity Framework application

This article will walk you through about implementation of paging and sorting of table in ASP.NET MVC and Entity Framework application. For paging we will use PageList.MVC NuGet package, it is one of the best package for paging and sorting. We will display model list details in table format and perform paging and sorting on it.
For this tutorial we will use Products table from Northwind database. Northwind database.

Implementation of Paging and Sorting in ASP.NET MVC

  1. Create New ASP.NET MVC Application

    Open Visual studio and create new ASP.NET MVC application clicking File -> New -> Project and select ASP.NET MVC4 Web Application name it as NorthwindApp
    From next window select Internet Application and Razor as view engine. Click Ok.
  2. Add ASP.NET MVC Model for NorthwindEntities

    I assume that you have Northwind database on your local SQL Server or any accessible SQL Server to you.
    Right Click Models folder from Visual Studio Solution Explorer. And select Add -> New Item
    From next Window's Installed Pane select ADO.NET Entity Data Model Add ADO.NET Entity Data Model

    From next window select Generate from database and click next.
    From next window if you have existing connection string to Northwind database select it or create new connection by clicking New Connection button. Click Next.
    From next window select Products table and click finish. Products.edmx file will be created under Models folder.
  3. Install PageList.MVC NuGet Package

    Go to Solution Explorer and right click on References and select Manage NuGet Package.
    From next window's Installed Packages select Online tab and enter paged in search box which is on upper right corner of popup box.
    In search result you will see PageList.MVC click install and close. It will add required References and css files for paging.
    ASP.NET MVC PageList
  4. Create ProductController

    Add new controller named as ProductController to handle product related requests.
    Right click on Controllers folder from Solution Explorer and select Add -> Controller. Give controller name as ProductController and select Empty MVC Controller.
    Add using statements for NorthwindApp.Models and PagedList to ProductController.
    Your controller code will look like this
    using NorthwindApp.Models;
    using PagedList;
    
    namespace NorthwindApp.Controllers
    {
        public class ProductController : Controller
        {
            northwindEntities _db;
    
            public ProductController()
            {
                _db = new northwindEntities(); 
            }
    
            public ActionResult Index(string sortOrder, string CurrentSort, int? page)
            {
                int pageSize = 10;
                int pageIndex = 1;
                pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;
                
                ViewBag.CurrentSort = sortOrder;
    
                sortOrder = String.IsNullOrEmpty(sortOrder) ? "ProductID" : sortOrder;
    
                IPagedList<Product> products = null;
                
                switch (sortOrder)
                {
                    case "ProductID":
                        if(sortOrder.Equals(CurrentSort))  
                            products = _db.Products.OrderByDescending
                                    (m => m.ProductID).ToPagedList(pageIndex, pageSize);   
                        else
                            products = _db.Products.OrderBy
                                    (m => m.ProductID).ToPagedList(pageIndex, pageSize);   
                        break;
                    case "ProductName":
                        if (sortOrder.Equals(CurrentSort))  
                            products = _db.Products.OrderByDescending
                                      (m => m.ProductName).ToPagedList(pageIndex, pageSize);
                        else
                            products = _db.Products.OrderBy
                                        (m => m.ProductName).ToPagedList(pageIndex, pageSize);
                        break;
                    
                    // Add sorting statements for other columns
                    
                    case "Default":
                        products = _db.Products.OrderBy
                                (m => m.ProductID).ToPagedList(pageIndex, pageSize);
                        break; 
                }
                return View(products);
            }
        }
    }           
    • _db: variable declared to represent Northwind database.
    • Constructor: declared to create an instance of northwindEntities.
    • Controller Action Index: Created to fetch product list of Products from Northwind database. It accepts three parameters string sortOrder, string CurrentSort, int? page. If sortOrder and CurrentSort are same sorting will be done in desc order. Input parameter page indicates the page number.
    • If the parameter page is null then paging will be done for pageIndex 1. If sortOrder is null or empty then sorting will be done on "ProductID".
    • sortOrder parameter value saved to ViewBag.CurrentSort for deciding on desc order sorting on next sorting request.
    • .ToPagedList(pageIndex, pageSize) will perform the indexing depending on pageIndex and pageSize value.
  5. Products View

    Open Solution Explorer and add new folder Product under Views.
    Add new view under Product folder by right clicking on Product folder and select Add -> View. Give View name as Index and select Razor as View engine.
    Add below HTML to Index.cshtml
    @model PagedList.IPagedList<northwindapp.models.product>
    
    @using PagedList.Mvc;
    @{
        ViewBag.Title = "Product List";    
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>Product List</h2>
    
    @using (Html.BeginForm())
    {      
        <table>
            <tr>
                <th style="border: 2px solid black; text-align: center; width: 12%">                
                     @Html.ActionLink("Product ID", "Index", 
                            new { sortOrder = "ProductID", CurrentSort = ViewBag.CurrentSort })
                </th>
                <th style="border: 2px solid black; text-align: center; width: 25%">
                     @Html.ActionLink("Product Name", "Index", 
                            new { sortOrder = "ProductName",  CurrentSort = ViewBag.CurrentSort })
                </th>
                <th style="border: 2px solid black; text-align: center; width: 15%;">
                    @Html.ActionLink("Qty", "Index", 
                            new { sortOrder = "QuantityPerUnit", CurrentSort = ViewBag.CurrentSort })
                </th>
                <th style="border: 2px solid black; text-align: center; width: 10%;">
                    @Html.ActionLink("Unit Price", "Index", 
                            new { sortOrder = "UnitPrice", CurrentSort = ViewBag.CurrentSort }) 
                </th>
                <th style="border: 2px solid black; text-align: center; width: 10%;">
                    @Html.ActionLink("Units In Stock", "Index", 
                            new { sortOrder = "UnitsInStock", CurrentSort = ViewBag.CurrentSort }) 
                </th>
            </tr>
            @foreach (var item in Model)
            {
                <tr>
                    <td style="border: 2px solid black; text-align: center; word-wrap: break-word;">
                        @Html.DisplayFor(modelItem => item.ProductID)
                    </td>
                    <td style="border: 2px solid black; text-align: center; word-wrap: break-word;">
                        @Html.DisplayFor(modelItem => item.ProductName)
                    </td>
                    <td style="border: 2px solid black; text-align: center; word-wrap: break-word;">
                        @Html.DisplayFor(modelItem => item.QuantityPerUnit)
                    </td>                
                    <td style="border: 2px solid black; text-align: center; word-wrap: break-word;">
                        @Html.DisplayFor(modelItem => item.UnitPrice)
                    </td>
                    <td style="border: 2px solid black; text-align: center; word-wrap: break-word;">
                        @Html.DisplayFor(modelItem => item.UnitsInStock)
                    </td>
                </tr>
            }
        </table> 
        <br />
        <div id='Paging' style="text-align:center">
            Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
            of @Model.PageCount
    
            @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
        </div>
    }           
                
    • This view is binded to PagedList.IPagedList<northwindapp.models.product> model.
    • _Layout.cshtml has set as master page.
    • Table is added to show product list.
    • Column headers are added as links, which executes the controller Index action method providing sortOrder and currentSort details.
    • Table rows and its cells are binded to Products Model data.
    • The div Paging will render paging controls.
  6. Browse Product List

    Browse below url to view product list. Replace the port number with your application's port number.
                http://localhost:54342/product/index
                
    ASP.NET MVC Paging for Northwind Products

If your paging controls are not displayed properly make sure PagedList.css located under Content folder is included in Index.cshtml or in Master page.

jQuery AJAX with Page Method example in ASP.NET

This article gives you step by step example for implementing WebMethod and calling it through jQuery.ajax() method.
This example will read data from Customer table of Northwind database. You can download Northwind database . Depending on selected Country value of DropDown, Customer details will be render if jQuery.ajax() call returns success.

jQuery.Ajax()

jQuery library functions and methods has capabilities to load data from server without a browser page refresh. jQuery.Ajax() performs an asynchronous http request. This method can handle response type of xml, json, script or html. If you are making a request to other domain datatype jsonp should be used. You can perform asynchronously GET, POST, PUT or DELETE methods on server using jQuery.Ajax().

Implementing PageMethod with jQuery.Ajax() in ASP.NET

  1. jQueryAJAX solution

    Create new solution of ASP.NET. Open visual studio click on File -> New -> Project -> ASP.NET Web Application name it as jQueryAjax and click Ok.
  2. Design Customer page

    Open Default.aspx or create new page with name Customer.aspx. In this step we will add a DropDownList control to give user to select particular Country. You can also try with jQuery
    We will also design a table object which will display Customer details on selection of Country. The jQuery change event of DropDownList will be used to add rows to table object.
    Add below html in BodyContent ContentPlaceHolder of Default.aspx.
    <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
        <div>
        Country:
        <asp:DropDownList ID="ddlCountry" runat="server">
            <asp:ListItem Text="Brazil" Value="Brazil"></asp:ListItem> 
            <asp:ListItem Text="France" Value="France"></asp:ListItem> 
            <asp:ListItem Text="Germany" Value="Germany"></asp:ListItem> 
            <asp:ListItem Text="Spain" Value="Spain"></asp:ListItem> 
            <asp:ListItem Text="USA" Value="USA"></asp:ListItem> 
            <asp:ListItem Text="UK" Value="UK"></asp:ListItem> 
            <asp:ListItem Text="Mexico" Value="Mexico"></asp:ListItem> 
        </asp:DropDownList> 
        </div>
        <br />
        <div>
        <table id="tblCustomers" class="tblCustomers" >            
            <thead>
                <tr>
                    <th align="left" class="customerth">CustomerID</th>    
                    <th align="left" class="customerth">CompanyName</th>    
                    <th align="left" class="customerth">ContactName</th>    
                    <th align="left" class="customerth">ContactTitle</th> 
                    <th align="left" class="customerth">City</th>
                    <th align="left" class="customerth">Phone</th>  
                </tr>
            </thead> 
            <tbody>
                
            </tbody> 
        </table>        
        </div>     
    </asp:Content>
    
                
  3. Apply css to Customer table

    Open Site.css from Styles folder and add below styles to it. These styles are applied to table, table header and table row objects.
        .tblCustomers
        {
            font-family: verdana,arial,sans-serif; 
            font-size:11px;
            color:#333333;
            border-width: 1px;
            border-color: #666666; 
            border-collapse: collapse;    
        }
    
        .customerth
        {
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #666666; 
            background-color: #dedede;   
        }
    
        .customertd
        {
            border-width: 1px; 
            padding: 8px; 
            border-style: solid; 
            border-color: #666666; 
            background-color: #ffffff;  
        }
                
  4. Customer Entity

    Add new class as Customer.cs. This class will be used to hold customer details. jQuery.ajax() method will get array of Customer object.
    Add below properties to Customer.cs
        public class Customer
        {
            public string CustomerID { get; set; }
            public string CompanyName { get; set; }
            public string ContactName { get; set; }
            public string ContactTitle { get; set; }
            public string City { get; set; }        
            public string Phone { get; set; }
        }
            
  5. PageMethod for jQuery.Ajax()

    Open codebehind file of Default.aspx page. In this file we will add a PageMethod which takes country as input parameter and return array of Customer object.
    It makes a database call to SQL Server and get customer details depending on provided country.
    Add below code in Default.aspx.cs file. Notice that we have added [System.Web.Services.WebMethod] for GetCustomers method which allows access to methods by scripting method.
    [System.Web.Services.WebMethod]
    public static Customer[]  GetCustomers(string country)
    {
        List<Customer> customers = new List<Customer>();
        string query = string.Format("SELECT [CustomerID], [CompanyName]," +
                 " [ContactName], [ContactTitle]," +
                 "[City], [Phone] FROM [Customers] " +
                   "WHERE Country LIKE '%{0}%'", country);
    
        using (SqlConnection con =
                new SqlConnection("your connection string"))
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                con.Open(); 
                SqlDataReader reader = cmd.ExecuteReader();
    
                while (reader.Read())
                {
                    Customer customer = new Customer();
                    customer.CustomerID = reader.GetString(0);
                    customer.CompanyName = reader.GetString(1);
                    customer.ContactName = reader.GetString(2);   
                    customer.ContactTitle = reader.GetString(3);
                    customer.City = reader.GetString(4);
                    customer.Phone = reader.GetString(5);
                    customers.Add(customer);   
                }
            }
        }
                
        return customers.ToArray();
    }
                
  6. jQuery.Ajax()

    In this step we will call PageMethod created in previous step. Create a new JavaScript file by open Solution Explorer -> right click on Scripts folder -> Select Add -> New Item -> Choose JScript -> Name it as Customer.js and click Ok
    Add function for ddlCountry DropDownList's change event. Whenever user will change selection of country, PageMethod will be called through jQuery.Ajax(). If call is successfull it will read Customer details and add each customer as table row to tblCustomers.
    $(document).ready(function () {
    
        $("#MainContent_ddlCountry").change(function () {
            
            $("#tblCustomers tbody tr").remove();
    
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetCustomers",
                data: '{country: "' + $(this).val() + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    response($.map(data.d, function (item) {
                        var rows = "<tr>"
                        + "<td class='customertd'>" + item.CustomerID + "</td>"
                        + "<td class='customertd'>" + item.CompanyName + "</td>"
                        + "<td class='customertd'>" + item.ContactName + "</td>"
                        + "<td class='customertd'>" + item.ContactTitle + "</td>"
                        + "<td class='customertd'>" + item.City + "</td>"
                        + "<td class='customertd'>" + item.Phone + "</td>"
                        +"</tr>";
                        $('#tblCustomers tbody').append(rows);
                    }))
                },
                failure: function (response) {
                    var r = jQuery.parseJSON(response.responseText);
                    alert("Message: " + r.Message);
                    alert("StackTrace: " + r.StackTrace);
                    alert("ExceptionType: " + r.ExceptionType);
                }
            });
        });
    });
    
    
    $("#tblCustomers tbody tr").remove(); removes existing rows from table object.
    Url is mentioned as "Default.aspx/GetCustomers" which indicates where your PageMethod exists.
    PageMethod takes country as input parameter which is mentioned with data property of $.ajax.
    success: function (data) { } will execute when PageMethod executes successfully. It add row for each customer record.
    failure: function (response) { } will execute if there is any error in execution of PageMethod and gives details of error.
  7. Add reference to script files

    Open Site.Master file and add reference to script file in head tag of Master page.
    Your head tag will look like this
    <head id="Head1" runat="server">
        <title></title>
        <link href="~/Styles/Site.css"
             rel="stylesheet" type="text/css" />
        <script language="javascript" type="text/javascript"
             src="Scripts/jquery-1.4.1.min.js"></script>  
        <script language="javascript"  
            type="text/javascript" src="Scripts/Customer.js"></script>  
        <asp:ContentPlaceHolder ID="HeadContent" runat="server">
        </asp:ContentPlaceHolder>
    </head>
    

read customer from server by jQuery Ajax