November 27, 2012

Should I use Cookies or Web Storage?

Cookies and Web Storage serve similar purpose in some and different purpose in many ways. Both cookies and web storage stores data on the client but cookies are sent back to the server on every request. So, if the data is needed to be used only by the client - then, its better to use web storage. However, if the data needs to be used by the server then cookies is the way. For example, for sessions, cookies is the definitely needed. Cookies, like web storage, can be accessed fom client side as well using javascript.

One more thing to note is that not all browsers support web storage yet - for example, Internet explorer 7-, Firefox 3.5- and Chrome 4- does no not support web storage. So, web storage may not be a solution on all situations.

Also, web storage can have maximum storage of 5MB whereas cookies have a maximum storage of 4KB.

Cookies can also have an expiration date - that is, it expires after some time period. On the other hand, web storage is of 2 types - local and session. Session storage is really like local storage except that it expires when the session ends.

November 17, 2012

Examining the Views

As mentioned in the previous article on accessing Model from Controller, Views for Index, Create, Edit, Delete and Details are automatically created. In this post, I will examine of Index View. The generated code for Index View is below.

November 16, 2012

As you might already know from my previous post on accessing Model from Controller, Visual Studio can automatically generate Controller class simply by right-clicking and adding Controller on the Controller's directory in Solution Explorer. The generated Controller code contains the following snippet.

November 15, 2012

Access Model from Controller

In one of my previous posts, I showed on how to add a Model to a Mvc project. Once we have a Model, it's important to access this Model from a Controller. In this post, I will show how to add a Controller that can access data from a Model and automatically create Views for CRUD operations. Asp.Net Mvc allows using Code First development. Using Code First, the database is automatically created based on the Model class and connection string within the web.config file.
From previous post, I created a CartoonCharacter class as the Model and added the following connection string.

November 12, 2012

Configure IIS 6.0 for Wildcard Mapping

Sometimes applications need to rewrite urls for producing user friendly urls and there are still lot of companies that use IIS 6.0. There are frameworks like Dynamic Data and Asp.Net Mvc that would rewrite urls and will not run in IIS 6.0 unless configured. This can be configured within IIS Manager. Once an application is added, it would look like below.

November 10, 2012

Adding a Model

Model classes holds the business logic and can perform data access and updates. Asp.Net Mvc can use Entity Framework for accessing data which supports Code First. In Code First, classes can be written which can then be used to create database on the fly.

To add a Model, right click on Models folder in Solution Explorer/Navigator, choose Add>Class. I have created the class CartoonCharacter for this.


Model - CartoonCharacter class
  1. public class CartoonCharacter
  2. {
  3.     public int Uid { get; set; }
  4.     public string FirstName { get; set; }
  5.     public string LastName { get; set; }
  6.     public int Year { get; set; }
  7.     public double Rating { get; set; }
  8. }

This ChartoonCharacter class will be used to represent ChartoonCharacters in a database. Each of the properties would be individual columns within a row. To use this class to perform data access/updates, a DataContext class needs to be added. This class is derived from Entity Framework and can handle CRUD operations. So, the final class looks like below.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Data.Entity;
  7. namespace MvcDemo.Models
  8. {
  9.     public class CartoonCharacter
  10.     {
  11.         public int Uid { get; set; }
  12.         public string FirstName { get; set; }
  13.         public string LastName { get; set; }
  14.         public int Year { get; set; }
  15.         public double Rating { get; set; }
  16.     }
  18.     public class CartoonCharacterDBContext : DbContext
  19.     {
  20.         public DbSet<CartoonCharacter> CartoonCharacters { get; set; }
  21.     }
  22. }

The CartoonCharacterDBContext class can now handle data operations. But, how does it know which database to connect to? The connection string needs to be setup within the web.config file so the DataContext class can connect to the database.

Connection String
  1. <connectionStrings>
  2.   <add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-MvcDemo-20121031221221;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
  3.       <add name="CartoonCharacterDBContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=CartoonCharacter;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
  4. </connectionStrings>

November 9, 2012

Pass Data from Controller to View

As mentioned in previous post on how Mvc work, Controller class handles browser request, gets data from database or other data source and selects the View to the user. Controller can therefore, retrieve data and pass data to the View. The View should not directly interact with the data source or handle any business logic but generate the HTML output based on the data provided from the Controller.

To show how we can pass data from Controller to View, I have added a new method Show() to the DemoController.cs file.

Show Method
  1. public ActionResult Show()
  2. {
  3.     List<string> list = new List<string>();
  4.     list.Add("Australia");
  5.     list.Add("Japan");
  6.     list.Add("USA");
  7.     list.Add("India");
  8.     ViewBag.List = list;
  10.     return View();
  11. }

The method creates a new List collection that holds string. This collection is then added to ViewBag.

Now, to create the View, right click on method name and choose Add View. Keep default settings and the file will be created.



In the file created, I have added a foreach loop to display the strings.

foeeach loop
  1. <ul>
  2.     @foreach (string a in ViewBag.List) {
  3.         <li>@a</li>    
  4.     }
  5. </ul>

When the page is run, the list of string displayed in the browser in the same order.

So, this example was quite simple that only strings was passed from Controller to View. I will now add a new method that will create some objects of type CartoonCharacter and pass back to View. So, first, here is the code for CartoonCharacter class. It is a simple class in that it only has first name and last name.

CartoonCharacter class
  1. public class CartoonCharacter
  2. {
  3.     public string FirstName { get; set; }
  4.     public string LastName { get; set; }
  5. }

Then, I will add the new method like below.

ShowCharacter method
  1. public ActionResult ShowCharacter()
  2. {
  3.     List<CartoonCharacter> list = new List<CartoonCharacter>();
  4.     list.Add(new CartoonCharacter { FirstName = "Yogi", LastName = "Bear" });
  5.     list.Add(new CartoonCharacter { FirstName = "Bugs", LastName = "Bunny" });
  6.     list.Add(new CartoonCharacter { FirstName = "Daffy", LastName = "Duck" });
  7.     list.Add(new CartoonCharacter { FirstName = "Scooby", LastName = "Doo" });
  8.     ViewBag.List = list;
  10.     return View();
  11. }

After the method added, right click on the method to add a View and keep default settings. Then, in the View, I have written another foreach loop that loops through the CartoonCharacter List and displays its first and last name.

foreach loop
  1. <ul>
  2. @foreach(MvcDemo.Controllers.CartoonCharacter cc in ViewBag.List){
  3.     <li>@cc.FirstName @cc.LastName</li>
  4. }
  5. </ul>

November 8, 2012

Default Layout in Asp.Net Mvc

In the previous post, I showed how to add a View to an Mvc project. The resultant page looked like below.

Mvc - Layout file
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <head>
  4.         <meta charset="utf-8" />
  5.         <title>@ViewBag.Title - My ASP.NET MVC Application</title>
  6.         <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
  7.         <meta name="viewport" content="width=device-width" />
  8.         @Styles.Render("~/Content/css")
  9.         @Scripts.Render("~/bundles/modernizr")
  10.     </head>
  11.     <body>
  12.         <header>
  13.             <div class="content-wrapper">
  14.                 <div class="float-left">
  15.                     <p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p>
  16.                 </div>
  17.                 <div class="float-right">
  18.                     <section id="login">
  19.                         @Html.Partial("_LoginPartial")
  20.                     </section>
  21.                     <nav>
  22.                         <ul id="menu">
  23.                             <li>@Html.ActionLink("Home", "Index", "Home")</li>
  24.                             <li>@Html.ActionLink("About", "About", "Home")</li>
  25.                             <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
  26.                         </ul>
  27.                     </nav>
  28.                 </div>
  29.             </div>
  30.         </header>
  31.         <div id="body">
  32.             @RenderSection("featured", required: false)
  33.             <section class="content-wrapper main-content clear-fix">
  34.                 @RenderBody()
  35.             </section>
  36.         </div>
  37.         <footer>
  38.             <div class="content-wrapper">
  39.                 <div class="float-left">
  40.                     <p>&copy; @DateTime.Now.Year - My ASP.NET MVC Application</p>
  41.                 </div>
  42.             </div>
  43.         </footer>
  45.         @Scripts.Render("~/bundles/jquery")
  46.         @RenderSection("scripts", required: false)
  47.     </body>
  48. </html>

As can be seen, the content section is the section that was rendered by the Welcome View created. The question is how did the page got the header logo and links section. The page go this section from _Layout.cshtml file in Views/Shared folder. This Layout file is being rendered on all pages generated by this Mvc application. This is more like the master page in an aspx application where the aspx page gets content from master pages when set via the master property. Here is the source code for the default Layout file.

The title is set as

So, the page gets the title from ViewBag and appends some text " - My ASP.NET MVC"...

  1. <title>@ViewBag.Title - My ASP.NET MVC Application</title>

Couple of lines below, there are some Styles.Render and Scripts.Render tags.

  1. @Styles.Render("~/Content/css")
  2. @Scripts.Render("~/bundles/modernizr")

These tags loads the default styles and scripts as specified in App_Start/BundleConfig.cs file. This file looks bundling all necessary scripts and stylesheets into one. The BundleConfig file looks like below.

  1. using System.Web;
  2. using System.Web.Optimization;
  4. namespace MvcDemo
  5. {
  6.     public class BundleConfig
  7.     {
  8.         // For more information on Bundling, visit
  9.         public static void RegisterBundles(BundleCollection bundles)
  10.         {
  11.             bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
  12.                         "~/Scripts/jquery-{version}.js"));
  14.             bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
  15.                         "~/Scripts/jquery-ui-{version}.js"));
  17.             bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
  18.                         "~/Scripts/jquery.unobtrusive*",
  19.                         "~/Scripts/jquery.validate*"));
  21.             // Use the development version of Modernizr to develop with and learn from. Then, when you're
  22.             // ready for production, use the build tool at to pick only the tests you need.
  23.             bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
  24.                         "~/Scripts/modernizr-*"));
  26.             bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
  28.             bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
  29.                         "~/Content/themes/base/jquery.ui.core.css",
  30.                         "~/Content/themes/base/jquery.ui.resizable.css",
  31.                         "~/Content/themes/base/jquery.ui.selectable.css",
  32.                         "~/Content/themes/base/jquery.ui.accordion.css",
  33.                         "~/Content/themes/base/jquery.ui.autocomplete.css",
  34.                         "~/Content/themes/base/jquery.ui.button.css",
  35.                         "~/Content/themes/base/jquery.ui.dialog.css",
  36.                         "~/Content/themes/base/jquery.ui.slider.css",
  37.                         "~/Content/themes/base/jquery.ui.tabs.css",
  38.                         "~/Content/themes/base/jquery.ui.datepicker.css",
  39.                         "~/Content/themes/base/jquery.ui.progressbar.css",
  40.                         "~/Content/themes/base/jquery.ui.theme.css"));
  41.         }
  42.     }
  43. }

The header menu is specified by @Html.ActionLink method. as follows.

Navigation menu
  1. <nav>
  2.     <ul id="menu">
  3.         <li>@Html.ActionLink("Home", "Index", "Home")</li>
  4.         <li>@Html.ActionLink("About", "About", "Home")</li>
  5.         <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
  6.     </ul>
  7. </nav>

The other important bit to note is the @RenderBody() method. This is the placeholder where the content from other Views will appear. For example, from previous post, the Welcome View would be rendered where @RenderBody() is specified.

Now, to modify the layout file, basic html knowledge sufficient to update the layout of the site. New styles or scripts can be written and called from the Layout file either directly or by using the BundleConfig file.

November 7, 2012

Add a View to Asp.Net Mvc

In the previous post, I showed how to add a Controller to an Mvc project. As you could see, html rendered in the page was done by Controller. In this post, I will show how to add a View to an Mvc project. The View is more like a template that can generate html output to the user. For this example, I have used Razor as the View engine.

The Demo Controller class created in the previous post looks like below.

  1. public class DemoController : Controller
  2. {
  3.     public string Index()
  4.     {
  5.         return "You are viewing Index method of DemoController";
  6.     }
  8.     public string Home(string name, int age)
  9.     {
  10.         return "Hello " + name + ". You are " + age.ToString() + " years old";
  11.     }
  12. }

Now, I will add a new method – Welcome that will return the View.

  1. public ActionResult Welcome()
  2. {
  3.     return View();
  4. }

To create a View, right click on method name and Add View.



Note that, I have left the default settings and names. The default View has the following code.

Welcome View
  1. @{
  2.     ViewBag.Title = "Welcome";
  3. }
  5. <h2>Welcome</h2>

I have added some message, so the code will look like below.

Welcome View
  1. @{
  2.     ViewBag.Title = "Welcome";
  3. }
  5. <h2>Welcome</h2>
  6. <p>This is a demo welcome page</p>

When the page is run, it looks like below.

Welcome - My ASP.NET MVC Application 2012-11-06 17-24-18

November 6, 2012

Run Asp.Net 4 under IIS6.0

Lately, I have trying to load a few web applications to run under IIS 6 and sometimes it became quite challenging. Eventually, I got them working and here are the steps that I used to run the applications.

Make sure .NET framework 4 is installed. You can do so by checking "Add Remove Programs" from Control Panel.

Once .NET 4 is installed, open IIS and open the Web Sections section. Click "Allow" for Asp.Net 4 if it not already allowed.


After that, create a new app pool that will only contain 4 applications. The IIS will not serve pages correctly if 4 and 3.5 are hosted in same app pool. Default configuration for app pool can be used.


Once the app pool is created, create a virtual directory for the web application. Choose the app pool created in previous step in the App Pool in Virtual Directory section. Open Asp.Net tab, and select 4.0 for version.


That's it - you are done. You can run the website. I have noticed in some windows 2003 server that while choosing 4 as the version, the sites go down. If so, go to Services and restart "World Wide Web Publishing" service.

November 1, 2012

In Asp.Net Mvc, Controllers are classes that query or update model data, load a specific View template and handle user inputs. Controllers can be added in an Mvc project by right clicking the Controllers directory and choosing Add > Controller.


I have named the Controller - DemoController - note the naming convention.


Visual Studio generates the following code by default.

Default Controller Code
  1. namespace MvcDemo.Controllers
  2. {
  3.     public class DemoController : Controller
  4.     {
  5.         //
  6.         // GET: /Demo/
  8.         public ActionResult Index()
  9.         {
  10.             return View();
  11.         }
  13.     }
  14. }

I will update the Index() method to return some string.

Index Method
  1. public string Index()
  2. {
  3.     return "You are viewing Index method od DemoController";
  4. }

Note that, I have changed the return type from ActionResult to string. Then, run the page in debug mode and the url http://localhost:50376/demo produce the result shown below. As you can see, its the same string that was part of the Index method.


The important thing to note is the url ends with /demo which is also the Controller’s name. In Mvc, the url controls the Controller, Method and parameters passed to the application. It has the format /Controller/Method/{Parameters} . Index is the default method name and therefore not needed to be specified.

I will now add another method - Home – that will display the name and age based on parameters.

Home Method
  1. public string Home(string name, int age)
  2. {
  3.     return "Hello " + name + ". You are " + age.ToString() + " years old";
  4. }

It’s a simple method that return a string based on the parameters. When the page is run, the following is displayed.


Note that, MVC automatically binds the query strings to the relevant parameters in the method.

What is MVC?

In my previous post, I should how to create a MVC project using Visual Studio but what is MVC? MVC, acronym for Model-View-Controller, is a software design pattern that separates the presentation (View), data model (Model) and user input based actions (Controller). In other words, it separates user interface logic from business logic.

View - The View manages the user interface, layout, etc. It can request information from Model about its state.

Controller - The Controller gets input from the View to update data and pass the message back to Model or to change the View.

Model - The Model controls the logic and behaviour of data. It pass data back to Controller when Controller asks for it and / or updates data when it receives message from Controller.

It's important to note that Model does not rely on Controller or View meaning that the Model can be created and tested separately from the user interface.

To relate this back to the MVC project created previously, there were separate folders for Model, Views and Controllers that manages how user with teh View, how View interacts with Model and responds to Controller and Controller talks to Model and View.

This should become more clear as I post more on this topic.

October 31, 2012

In this post, I will show how to create an MVC 4.0 project using Visual Studio 10 SP1. The built in templates in Visual Studio makes it easy to start creating the application. In the screenshot below, I have opened Visual Studio, and creating a new MVC 4.0 project using .NET 4.0 . I have called the solution MvcDemo.


After clicking OK, I will choose Internet Application as the template and Razor as the view engine and also create unit test project.


Visual Studio creates a working application once the OK button is hit. Folders and files have been created by default for Controllers, Models, Views, Filters, Scripts, Contents, etc. The screen shot below shows the full structure.


The application can now be started in Debug mode by hitting F5.


The application, by default, shows some informative messages. It’s important to note that the data for this page is obtained from Index.cshtml View which is under the Home sub-folder of View folder. The View contains mostly static content and dynamically obtains some information referred ViewBag.Message and ViewBag.Title property as shown below.


The value of ViewBag.Title property is set in the first couple of lines within the View. The ViewBag.Message property is set within the Index() method of HomeController class which is located within the Controller directory.

  1. namespace MvcDemo.Controllers
  2. {
  3.     public class HomeController : Controller
  4.     {
  5.         public ActionResult Index()
  6.         {
  7.             ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
  9.             return View();
  10.         }

October 27, 2012

The built in ModalPopupExtender of Ajax Control Tookit makes it very easy to implement modal windows in The extender have options for the location of the popup, drag feature, drag handle and option for styling the background and animating the popup. In this post, I will setup an animated Modal Popup with drag feature.

The code for the ModalPopupExtender is below.

Modal Popup Extender
  1. <asp:Button ID="Button1" runat="server" Text="Modal" />
  2. <cc:ModalPopupExtender ID="ModalPopupExtender1" runat="server" CancelControlID="BCancel" Drag="true" OkControlID="BOk" PopupControlID="PModal" PopupDragHandleControlID="PHandle" TargetControlID="Button1" BackgroundCssClass="bModal">
  3.     <Animations>
  4.         <OnShown>
  5.             <FadeIn Duration="0.8" Fps="40" />
  6.         </OnShown>
  7.         <OnHiding>
  8.             <FadeOut Duration="0.8" Fps="40" />
  9.         </OnHiding>
  10.     </Animations>
  12. </cc:ModalPopupExtender>

The PopupControlID is the id of the control that will be displayed when the button (TargetControlID) is clicked. The Drag property determines if the popup can be dragged and PopupDragHandleControlID property determines the control that can be dragged. If PopupDragHandleControlID is not set, the popup can be dragged from anywhere within the popup. The Animation section determines the animations properties of the popup. In this example, I have set 0.8 seconds for fade in and dade out.

The code for the popup control (an asp Panel control in my example) is below.

Popup Panel
  1. <asp:Panel ID="PModal" runat="server">
  2.     <asp:Panel ID="PHandle" runat="server" CssClass="modalHandle">Popup Title
  3.     <span style="float:right;"><asp:Button ID="BCancel" runat="server" Text="X" CssClass="closeModal" />    </span>
  4.     <br />
  5.     </asp:Panel>
  7.     <div class="modalContent">some content some content some content<br /> some content some content some content <br /><br />
  8.         <asp:Button ID="BOk" runat="server" Text="Ok" />
  10.     </div>
  11. </asp:Panel>

As can be seen, there is a nested Panel with id PHandle with a css class associated with it. This Panel will be used for dragging the control. It also contains the Cancel Button for closing the window. There is another nested div element that contains the contents for the popup. Then, there is the Ok button, which when clicked can do a postback and close the popup.

I have added css to different elements including the popup, background when popup is shown, drag handle and close button. The css code is below.

  1. <style type="text/css">
  2. .bModal { background-color:#eee; opacity:0.6; filter:alpha(opacity=60);}
  3. .modalContent { background-color:#fff; border:1px solid #ccc; width:400px; padding:2px 4px;}
  4. .modalHandle { background-color:#ccc; cursor:move; height:18px; padding:2px 4px; font-weight:bold;}
  5. .closeModal { background-color:#ccc; color:#fff; font-weight:bold; border:0;}
  6. </style>

In my example, the popup has been activated when the Button is clicked. The popup could also have been shown from the server side - for example, from Page Load event like below.

Page Load event
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  4.     ModalPopupExtender1.Show();
  5. }

Please note, if the popup doesn't need a button to be triggered, then the button os some other control still need to added on the page and can be hidden by using css like below. If the TargetControlId is left blank, the popup will not work.

Screen shot for the popup is below.


October 24, 2012

GridView can be used to display tabular data. Sometimes, instead of paging data, it might be user friendly to display all data in a scrollable format.

It's quite easy to implement this using CSS. In the example below, I have got a div element with a GridView in it and have applied styles to the div to allow scrolling. 

  1. <div style="height:200px; overflow:scroll;">
  2.     <asp:GridView ID="Gv2" runat="server" AutoGenerateColumns="true"
  3.             DataKeyNames="Uid" DataSourceID="EntityDataSource2">
  4.     </asp:GridView>
  6.     <asp:EntityDataSource ID="EntityDataSource2" runat="server"
  7.         ConnectionString="name=ProductsEntities"
  8.         DefaultContainerName="ProductsEntities" EnableFlattening="False"
  9.         EntitySetName="Products">
  10.     </asp:EntityDataSource>    
  11. </div>

October 23, 2012

GridView offers ways to customise row and alternate rows' properties. Sometimes it might be useful to highlight certain rows based on the data it contains. For example, we might have a gridview for products and we might want to highlight rows whose products have price less than 100, etc. In this example, I will use entity data source to bind the gridview and based on the price value, highlight the background colour using the RowCreated event.

Here is the code for it.

GridView Markup
  1. <asp:GridView ID="Gv1" runat="server" AutoGenerateColumns="False"
  2.     DataSourceID="EntityDataSource1" OnRowCreated="RowCreated" DataKeyNames="Uid">
  3.     <Columns>            
  4.         <asp:BoundField DataField="ProductId" HeaderText="ProductId"
  5.             SortExpression="ProductId" />
  6.         <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />            
  7.     </Columns>
  8. </asp:GridView>
  11. <asp:EntityDataSource ID="EntityDataSource1" runat="server"
  12.     ConnectionString="name=ProductsEntities"
  13.     DefaultContainerName="ProductsEntities" EnableFlattening="False"
  14.     EntitySetName="PriceHistories">
  15. </asp:EntityDataSource>
Row Created Event
  1. protected void RowCreated(object sender, GridViewRowEventArgs e)
  2. {
  3.     if (e.Row.DataItem != null)
  4.     {
  5.         double price = (double)((PriceHistory)e.Row.DataItem).Price.Value;
  7.         if (price > 100)
  8.             e.Row.BackColor = System.Drawing.Color.FromArgb(200, 200, 100);
  9.     }
  10. }

You might be wondering what PriceHistory class is - this class is defined within the entity model.

GridView is a data control that supports displaying data in a grid layout which is essentially an html table. It has built in support for updating, deleting, sorting and paging data, however, its lack of flexible layout makes it not the best option. For example, if we want to display the result of a search, we don't necessarily want to display the data in a tabular format.

This is where ListView comes in - it provides a highly customisable and flexible layout. ListViwe can contain any html elements in it like div, p, li, table and any other server side controls. Like GridView, it supports updating, deleting and sorting data. It also supports inserting and data grouping. Paging is also supported via DataPager control.

The following is an example of the how to declare and use GridView and ListView.

  1. <asp:GridView ID="gv" runat="server" AllowPaging="True" AllowSorting="True"
  2.     CellPadding="4" ForeColor="#333333" GridLines="None" EmptyDataText="Data not found">
  3.     <AlternatingRowStyle BackColor="White" />
  4.     <Columns>
  5.         <asp:CommandField ShowEditButton="True" />
  6.         <asp:CommandField ShowSelectButton="True" />
  7.         <asp:CommandField ShowDeleteButton="True" />
  8.     </Columns>
  9.     <EditRowStyle BackColor="#2461BF" />
  10.     <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  11.     <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  12.     <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
  13.     <RowStyle BackColor="#EFF3FB" />
  14.     <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
  15.     <SortedAscendingCellStyle BackColor="#F5F7FB" />
  16.     <SortedAscendingHeaderStyle BackColor="#6D95E1" />
  17.     <SortedDescendingCellStyle BackColor="#E9EBEF" />
  18.     <SortedDescendingHeaderStyle BackColor="#4870BE" />
  19. </asp:GridView>


  1. <asp:ListView ID="LView" runat="server" GroupItemCount="3" GroupPlaceholderID="groupPlaceHolder">
  2.     <LayoutTemplate>
  3.         <div class="layout"><asp:PlaceHolder ID="itemPlaceHolder" runat="server"></asp:PlaceHolder></div>
  5.         <asp:DataPager runat="server" ID="ColDataPager" PageSize="10" DataKeyNames="ID"
  6.             OnItemInserted="LView_Insert" InsertItemPosition="LastItem">
  7.           <Fields>
  8.             <asp:NextPreviousPagerField
  9.               ShowFirstPageButton="true" ShowLastPageButton="true"
  10.               FirstPageText="First " LastPageText=" Last"
  11.               NextPageText=" Next " PreviousPageText=" Prev " />
  12.           </Fields>
  13.         </asp:DataPager>
  14.     </LayoutTemplate>
  16.     <GroupTemplate>
  17.         <ul><li>
  18.             <asp:PlaceHolder runat="server" ID="groupPlaceHolder"></asp:PlaceHolder>
  19.         </li></ul>
  20.     </GroupTemplate>
  22.     <ItemTemplate>
  23.         <span class="l1_n"><%#Eval("column1") %></span>
  24.     </ItemTemplate>
  26.     <AlternatingItemTemplate>
  27.         <span class="l1_alt"><%#Eval("column1") %></span>
  28.     </AlternatingItemTemplate>
  30.     <ItemSeparatorTemplate>
  31.         <hr />
  32.     </ItemSeparatorTemplate>
  35.     <InsertItemTemplate>
  36.         <asp:Label runat="server" ID="LColumn1" AssociatedControlID="TBColumn1" Text="Column1"/>
  37.         <asp:TextBox ID="TBColumn1" runat="server" Text='<%#Bind("column1") %>' /><br />
  38.         <asp:LinkButton ID="LbInsert" runat="server" CommandName="Insert" Text="Insert" />
  39.     </InsertItemTemplate>
  41. </asp:ListView>

As you can see, it is lot easier to declare and use the GridView compare to ListView, however, the resultant view is more user friendly with ListView as long as you don't enter weird styles for the controls.

Reference: Shahed Kazi at