# Tuesday, March 25, 2014
Tuesday, March 25, 2014 1:16:00 AM (GMT Standard Time, UTC+00:00)
# Monday, December 16, 2013

Episode 296

Ward Bell on Breeze

Monday, December 16, 2013 10:58:00 PM (GMT Standard Time, UTC+00:00)
# Monday, September 30, 2013
Monday, September 30, 2013 8:57:00 PM (GMT Daylight Time, UTC+01:00)
# Monday, August 12, 2013
Monday, August 12, 2013 11:50:20 AM (GMT Daylight Time, UTC+01:00)
# Monday, June 3, 2013
Monday, June 3, 2013 7:10:00 PM (GMT Daylight Time, UTC+01:00)
# Monday, May 20, 2013
Monday, May 20, 2013 7:07:00 PM (GMT Daylight Time, UTC+01:00)
# Wednesday, March 13, 2013
Wednesday, March 13, 2013 5:14:15 PM (GMT Standard Time, UTC+00:00)
# Monday, October 8, 2012
Monday, October 8, 2012 12:23:01 PM (GMT Daylight Time, UTC+01:00)
# Tuesday, August 21, 2012
Tuesday, August 21, 2012 4:27:41 AM (GMT Daylight Time, UTC+01:00)
# Wednesday, July 18, 2012

Yesterday, I had the pleasure of presenting at the aspconf online conference. I delivered 2 presentations: HTML5 is the Future of the Web; and Using Windows Azure Storage.

As promised, my slides and demos are available by clicking the links below.

   
Wednesday, July 18, 2012 3:43:00 PM (GMT Daylight Time, UTC+01:00)
# Monday, April 23, 2012
Monday, April 23, 2012 9:37:00 PM (GMT Daylight Time, UTC+01:00)
# Monday, November 28, 2011
Monday, November 28, 2011 4:14:00 PM (GMT Standard Time, UTC+00:00)
# Monday, February 7, 2011
Monday, February 7, 2011 1:35:00 PM (GMT Standard Time, UTC+00:00)
# Monday, August 2, 2010
Monday, August 2, 2010 1:23:42 PM (GMT Daylight Time, UTC+01:00)
# Monday, January 25, 2010

Episode 65

Wrox just released a new book 'Testing ASP.Net web applications' by Jeff McWherter and Ben Hall. In this interview, Jeff and Ben discuss the importance of testing, the different types of tests and how to effectively test your web application.

Monday, January 25, 2010 5:04:09 AM (GMT Standard Time, UTC+00:00)
# Wednesday, October 7, 2009

Episode 58

In this interview, Sai Naik describes the advantages of SharePoint and where it is a recommended solution.

Wednesday, October 7, 2009 2:43:04 PM (GMT Daylight Time, UTC+01:00)
# Tuesday, October 6, 2009

The ASP.NET MVC framework (which I will refer to as "MVC" in this article) encourages greater separation of concerns than the older ASP.NET web forms framework.

Some key differences between web forms and  MVC are

  • ASPX pages in MVC have no code-behind files. This discourages developers from putting any business logic in the view.
  • By default, URLs in MVC do not point to a file on disc. Rather, they point to an Action in a Controller.

A controller is a class that inherits from System.Web.Mvc.ControllerBase.

MVC uses several conventions to find this class. First, it expects controller classes to be in the Controllers folder. Also, it expects a controller class name to end with "Controller".  So if we tell MVC to look for a Product controller, it will look for the file Controllers\ProductController.cs or Controllers\ProductController.vb.

An Action is a method within a Controller class that returns a System.Web.Mvc.ActionResult. The ActionResult represents the View data that is available when MVC renders output to the client.

One way we can tell MVC to look for a controller is by typing a URL into the browser’s address bar. Doing this causes MVC to use the routing engine. I described the routing engine in a previous article. The default routing assigned to a new MVC project looks for a URL with the following format

Controller/action/id

When the routing engine encounters a URL formatted like the one above, it looks for a controller named after the first part of the URL; an action method within that controller named after the second part of the URL; and a parameter to pass to that method in the third part of the URL. For example, if the user typed the following URL into the address bar:

Customer/Details/1

, MVC would look for a class named CustomerController in Controller\CustomerController.cs (assuming we are coding in C#). If it found this class, it would look in it for a method named "Details" that returns an ActionResult and that accepts a parameter. It would then call the Details method and pass it the parameter "1".

The ActionResult returned by this method is used by the MVC View engine to render output to the client. I described MVC views in a previous article.

The code below is for a Controller Action method. It assumes the existence of the GetCustomer method that returns a single customer object.

public ActionResult Details(Int32 id)
{
    Customer cust = MVCDemoRepository.GetCustomer(id);
    return View(cust);
}

The View method called in the code above returns a ViewResult – a class that inherits from ActionResult. By passing the Customer object to this method, the ActionResult’s Model property is populated with the Customer object. Properties of that object can then be used within the view.

Another way to pass data from the controller to the view is to populate the ViewData property. ViewData is a list of name-value pairs. You can populate this list in the controller and retrieve elements from it within the view. We can modify the Action method above to add to the ViewData list.

public ActionResult Details(Int32 id)
{
    ViewData["HelloMessage"] = "Good morning to you";
    Customer cust = MVCDemoRepository.GetCustomer(id);
    ViewData["GoodbyeMessage"] = "Good night. See you later";
    return View(cust);
}

By default, this controller routes the user to a view with the same name as the Action in a folder named after the controller. In this case, MVC will look in the \Views\Customer folder for a file named either Details.aspx or Details.ascx. If it cannot find either of these files in that folder, it will search in the Views\Shared folder. Here MVC is using configuration again to determine where to look for files.

You can change the view MVC looks for by using an overload of the View method as in the following example

return View("CustomerDetails", cust); 

The above line tells MVC to look for a view page named CustomerDetails.aspx or CustomerDetails.ascx in either \Views\Customer or \Views\Shared.

Here is a complete listing of a Controller class

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using MVCDemoController.Models;

namespace MVCDemoController.Controllers
{
    public class CustomerController : Controller
    {
        // GET: /Customer/
        public ActionResult Index()
        {
            List<Customer> customers = MVCDemoRepository.GetAllCustomers();
            return View(customers);
        }

        // GET: /Customer/Details/1
        public ActionResult Details(Int32 id)
        {
            ViewData["HelloMessage"] = "Good morning to you";
            Customer cust = MVCDemoRepository.GetCustomer(id);
            ViewData["GoodbyeMessage"] = "Good night. See you later";
            return View(cust);
        }
    }
}

Below is a sample view to render the output from the Details controller action above

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MVCDemoController.Models.Customer>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Details
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Details</h2>

    <div>
    <%=Html.Encode(ViewData["HelloMessage"]) %>
    </div>
    <fieldset>
        <legend>Fields</legend>
        <p>
            ID:
            <%= Html.Encode(Model.ID) %>
        </p>
        <p>
            FirstName:
            <%= Html.Encode(Model.FirstName) %>
        </p>
        <p>
            LastName:
            <%= Html.Encode(Model.LastName) %>
        </p>
    </fieldset>
    <p>
        <%=Html.ActionLink("Back to List", "Index") %>
    </p>
    <div>
    <%=Html.Encode(ViewData["GoodbyeMessage"]) %>
    </div>

</asp:Content>

Details

Good morning to you
Fields

ID: 1

FirstName: David

LastName: Giard

Back to List

Good night. See you later

The MVC Controller is used to retrieve data from the Model, to populate any extra data needed by the view and to determine which view to render. Understanding it is key to understaning MVC.

Download demo code for this article at MVCDemoController.zip (281.08 KB)

 

ASP.NET | MVC
Tuesday, October 6, 2009 5:10:09 AM (GMT Daylight Time, UTC+01:00)
# Sunday, October 4, 2009

The ASP.NET MVC framework (which I will refer to as "MVC" in this article) encourages developers to work closer to actual rendered HTML than does the more traditional web forms ASP.NET framework. The web form framework abstracted away much of the HTML, allowing developers to create sophisticated web pages simply by dragging controls onto a design surface. In fact, with the web forms framework, it is sometimes possible for someone with no knowledge of HTML to build an entire web application.

But MVC’s view engine removes that abstraction, encouraging users to write more of their own HTML. By doing so, developers also get more control over what is rendered to the client.

Some web developers may be surprised to learn that most of the server controls they are used to dragging onto a design surface do not work in MVC. This is because ASP.NET server controls are self-contained objects that encapsulate all their functionality, including the C# or VB code they run. This is contrary to the way that MVC works. In the MVC framework, all business logic code is in either the model (if it applies to the data) or in the controller if it applies to routing or output.

An MVC view consists only of an ASPX page. By default it doesn't even contain a code-behind file.

Let’s analyze a typical MVC view. Like a web form, an MVC view contains a page directive at the top.

<%@ Page Title="Sports" Language="C#" 
MasterPageFile="~/Views/Shared/Site.Master" 
Inherits="System.Web.Mvc.ViewPage<TestMvc.Models.Customer">
%>

The Title, Language and MasterPageFile attributes should be familiar to anyone who has developed in ASP.NET. The meanings of these attributes have not changed in MVC. The Inherits attribute is also used in web forms development, but in this case, we are inheriting from a ViewPage that contains our model.  The model represents the data we wish to render (I will write more about the MVC model in a future article.) By inheriting from a ViewPage, we provide the model data directly to the page and we can strongly type the keyword Model to whatever data type our model is.

Mixed in with the HTML of our page, we can output some server side data by enclosing it in <% %> tags.

If you wrote any web sites with classic ASP (the predecessor to ASP.NET), you probably used these tags. (I recently heard someone refer to them as "bee stingers").  If you place "=" in front of a value or variable, the view engine will output the value or contents of that variable. For example

<%=System.DateTime.Now %>

outputs the current date and time, like the following

10/2/2009 6:08:46 PM

We mentioned earlier that the Model keyword is strongly-typed. For example, If we inherit our ASPX from  System.Web.Mvc.ViewPage<TestMvc.Models.Customer>, then our model represents a Customer object and we can output a property of that model class.

Assuming that our Model is uses the following Customer class:

public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

, we can output the FirstName property with the following markup:

<%= Model.FirstName %> 

You probably already know that it is almost always a bad idea to output text directly for the screen without encoding it, as I did above. Failure to do so may leave your site open to scripting attacks. Fortunately MVC includes an Encode helper method to encode strings for safer output. That helper method (along with other helpers) is available via the Html property of the ViewPage from which our view inherits. We can call the helper method and encode the first name with the following markup.

<%= Html.Encode(Model.FirstName) %>

This outputs the FirstName property, but encodes it to prevent problems if the first name property somehow gets infected with some client-side script.

Other helper methods of the ViewPage give you the ability to begin and end an HTML form, to render an HTML textbox, to render a hidden field, to render an HTML listbox, and perform many other useful functions.

The code below will output a hyperlink with the text "Home" that links to the Index method in the Home controller.

<%= Html.ActionLink("Home", "Index", "Home")%>

Another way to use data in the view is to store it in ViewData. ViewData is a property of the view and contains a dictionary of name/value pairs. You can add a value to this dictionary in the controller with code like the following

ViewData["Greetings"] = "Hello dummy";

and display a ViewData element in the view with markup like the following

<%= Html.Encode(ViewData["Greetings"]) %>

Below is the full markup for a sample MVC view page

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MVCDemoView.Models.Customer>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div>
<%= Html.Encode(ViewData["Greetings"]) %>
</div>
<div>
<%= Html.Encode(Model.FirstName) %>
<%= Html.Encode(Model.LastName) %>    
</div>
<div>
<%= Html.ActionLink("Home", "Index", "Home")%>
</div>
</asp:Content>

Here is the output of the view page above

Hello dummy
David Giard

If you don’t like the view engine that ships with MVC, it is possible to replace it with your own. Some open source projects, such as Spark have already given users this ability.

Using the MVC view engine encourages developers to have more control over the output sent to the client and provides a greater separation of concerns for the application as a whole.

Download the code for this sample at MVCDemoView.zip (281.64 KB)

ASP.NET | MVC
Sunday, October 4, 2009 8:38:29 PM (GMT Daylight Time, UTC+01:00)
# Friday, October 2, 2009

One of the differences between ASP.NET MVC  and traditional ASP.NET web forms is the URL typed by the user.

In traditional ASP.NET, a URL points to a physical page on disc. Typically one can infer the location of that page by examining the URL. For example, the URL

/Folder1/MyPage.aspx

likely points to a file named MyPage.aspx located in a folder named Folder1.

By contrast, a URL in an ASP.NET MVC application points to an action in a controller. For example, the URL

/Customer/Edit/2

Tells the MVC framework to pass a parameter of "2" to an action method named Edit in a Customer controller class.

ASP.NET MVC (which I’ll call MVC going forward) uses routing to map a URL to a specific action. Routing is typically configured in the  Application_OnStart method of the global.asax file.  An MVC application contains a System.Web.Routing.RouteTable, which contains a collection of routes on which it can act. When you create a new MVC project, a default route is added to this collection by adding the following code in global.asax.

routes.MapRoute(
    "Default",                                              // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
    );

This code adds a route named "Default" to the route table. This route tells MVC to look for a URL structured similar to the following

Controller/action/id

When it encounters such a URL, it looks for a controller class with a name based on the first part of the URL. By convention, MVC looks for controllers in the "Controllers" folder and is named with the suffix "Controller". So if the first part of the URL is "Customer", MVC will look in the controllers folder for a class derived from System.Web.Mvc.Controller named "CustomerController".

The second part of the URL identifies an action. The action is a method within the controller that returns a  System.Web.Mvc.ActionResult. The ActionResult identifies the view used to render a response (more on that in a later article). So if the second part of the URL is "Edit", MVC will look for a method in the controller class named "Edit" that returns an ActionResult.

The third part of the above URL defines a parameter for the action, in this case a parameter named "id".

The following URL

/Customer/Edit/2

causes MVC to search for a class named Controllers\CustomerController, to call the Edit method in this class and to pass the value 2 to the id parameter of the Edit method.

What if the URL does not contain all three parts? The Default route above specifies a default value for each of the parts. If the third part of the URL is omitted, no parameter is passed to the Action. For a URL with no id parameter, we will need to create an action method that does not expect a parameter. If the second part of the URL is omitted, the default action is "Index", so MVC will look for a method named "Index" in the controller class. If the first part of the URL is omitted, it defaults to "Home" so MVC will look for a Controller class named "HomeController" in the Controllers folder.

You can use this same syntax to add more routes to your application. Simply add more calls to routes.MapRoute() in Global.asax. MVC will match URLs to these routes in the order listed.

Notice that the RouteTable and RouteCollection are part of the System.Web.Routing namespace and not part of any MVC namespace. This should tell you that the routing engine is not restricted to MVC applications. It can be used in any ASP.NET application if you want cleaner URLs.

If you find a URL like /Customer/Edit/2 more asthetically pleasing than /Customers/EditCustomer.aspx?CustID=2, you should investigate the routing engine.

ASP.NET | MVC
Friday, October 2, 2009 2:21:00 PM (GMT Daylight Time, UTC+01:00)
# Thursday, October 1, 2009

Microsoft first released ASP.NET almost eight years ago. At that time, they created a model they hoped would be familiar (and compelling) to Windows forms developers, particularly to those working in Visual Basic 6.

ASP.NET adopted a development paradigm that mimicked Windows forms. This programming model was referred to as “web forms” and it abstracted away much of the complexity of HTML and HTTP, easing the transition from Windows to the web for many developers. Using web forms, developers could drag controls, such as buttons and textboxes, onto a design surface and add code that ran automatically when a user interacted with a control – such as when a user clicks a button. Pages and controls had events, such as Load and Init that ran at specified times during a page’s creation. By default, each page had a code-behind file – class containing code that responded to page events. These concepts were familiar to Visual Basic developers and this helped to drive adoption of ASP.NET.

But there are some drawbacks to this model. Web forms abstracted away the details of HTML and HTTP, but this abstraction cost the developer control over the rendering of pages and controls. Some developers felt that the web forms framework got in the way of their web developing by hiding these basic constructs. Also, tying code to web form events made it difficult to test much of the application. Testing frameworks evolved that would mimic the behavior of a web server, just to integrate with automated unit testing frameworks.

Recently Microsoft released ASP.NET MVC - a new programming framework designed to build web applications with HTML and HTTP. This framework uses the Model-View-Controller pattern.

The Model-View-Controller pattern is not new. However the release of ASP.NET MVC (I’ll refer to it as "MVC" going forward) has renewed interest in this pattern.

MVC consists of three main parts. You’ll never guess what they are. Give up? They are the Model, the View and the Controller.

The Model contains the application’s data and any business rules associated with that data. It is up to the Model to retrieve and update data from and to a database (or other persistent data store or back-end), to validate that data and to apply any business rules to that data.

The View is a template for the user interface. It should contain no logic at all. In fact, in the ASP.NET MVC framework, by default View web pages don’t even have a code-behind file. A view in this framework consists only of HTML mixed with some placeholders to output values from the model or helper functions based on those values.

The Controller is the glue that binds the Model to the View. By default, each web request in ASP.NET MVC gets routed to a given method (known as an “Action”) of a given class (known as a "Controller"). This method executes and returns either a view or enough information for the framework to identify and render a view.

MVC has two main advantages over web forms –It is easier to test and it gives more control to the developer.

Separating an application into three distinct parts makes it far easier to test.  Launching a user interface in an automated testing framework, such as NUnit or MSTest is possible but it’s clumsy and slow. Minimizing the code in the user interface allows us to test the code more easily.

MVC also gives the developer more control over the rendered HTML (the view) than is possible in web forms. Web forms deliberately abstract away much of the HTML rendering, while MVC forces the developer to write explicit HTML in his View templates.

The release of ASP.NET MVC certainly does not signal the end of web forms.  Many developers appreciate the abstraction that web forms provides for them. Many web forms still exist in production and I have yet to hear anyone refer to these as "legacy" applications or "Classic ASP.NET".

But for those who want more control over their output, a more pure separation of concerns and easier testability, ASP.NET MVC offers a good option.

ASP.NET | MVC
Thursday, October 1, 2009 1:39:21 PM (GMT Daylight Time, UTC+01:00)
# Saturday, August 22, 2009

I started using DasBlog for this blog almost two years ago.

For the past couple months, I've been struggling trying to add a permanent page to my web site. By permanent, I mean a page that is always relevant and is always available at the top of the site; as opposed to a blog post, which is dated and moves down as new blog posts are added.

My biggest problem is that I wanted the new page to have the same theme as all existing pages. It seemed simple enough but DasBlog did not provide an obvious way to do this.

Recently I discovered an old post by Omar Shahine at http://www.shahine.com/omar/FormatPageMacroInDasBlog.aspx

He described in detail exactly what I wanted to do.

Essentially, I create a file named xxx.format.html and add any static HTML I want on my new page. To apply the theme, I need to use FormatPage.aspx, which ships with DasBlog. FormatPage.aspx accepts a parameter path, which points to an HTML document and displays that document with the current theme applied.

After uploading my HTML page, I can apply a theme by linking to FormatPage.aspx?path=DaveSchedule.format.html.

Now I have a link in a tab at the top of every page pointing to my past and upcoming speaking schedule and that page has the same theme as the rest of the site.

Saturday, August 22, 2009 4:43:00 PM (GMT Daylight Time, UTC+01:00)
# Wednesday, August 27, 2008

Microsoft recently released the ASP.Net Model View Controller framework (MVC).  It is currently available as Preview 3 and can be downloaded at http://www.microsoft.com/downloads/details.aspx?FamilyId=92F2A8F0-9243-4697-8F9A-FCF6BC9F66AB&displaylang=en

A new MVC project contains a couple sample views and controllers so you can get an idea of the proper syntax to use. 

This article builds on the application created in my last ASP.Net MVC tutorial.  If you have not already done so, please follow the brief states in the previous MVC tutorial before beginning this tutorial

In the last tutorial, we added a model, view and controller to display a list of customers that one can navigate to using a URL formatted as controller/action.  In this article, we will add a new view and controller to an existing MVC project and display details of a single customer using a URL formatted as controller/action/id.  The id is passed automatically to the action method and allows us to filter to a single customer.

1.       Open Visual Studio 2008 and open the TestMVC solution created in MVC Tutorial 2.

2.       Open the Solution Explorer (View | Solution Explorer) and select the Controllers\CustomerController.cs.   Double-click CustomerController to open it in the code editor.

a.       In the CustomerController class, we will create a new action to get the details of a single customer.   

                                                               i.      Add the following private GetCustomer method to the CustomerController class.  In the last tutorial, we wrote methods to retrieve customer 1 and customer 2.  For simplicity, we will get Customer 1 if ID 1 is passed in to our method and Customer 2 if any other ID is passed.

        private Customer GetCustomer(int custID)

        {

            if (custID == 1)

            {

                return GetCustomer1();

            }

            else

            {

                return GetCustomer2();

            }

        }

                                                             ii.      Add an Action method to the CustomerController class to get the details of a customer.  Paste the following code into CustomerController.cs.

        public ActionResult Details(int id)

        {

            Customer cust = GetCustomer(id);

            return View("Details", cust);

        }

                                                            iii.      In the GetCustomer method, we get details of a single customer and return a view.  Unlike the generated code, we explicitly specify which view to return (“Details”) and we pass in some extra data (cust) that the view will consume.

3.       Add a view to the project.

a.       In the Solution Explorer, right-click the Views\Customer folder and select Add | New Item.  The Add New Item dialog displays.

    Figure 1

                                                               i.      Under Categories, select Visual C#\Web\MVC.

                                                             ii.      Under Templates, select  MVC View Content Page.

                                                            iii.      In the Name textbox, enter “Details”.

                                                           iv.      The Select a Master Page dialog displays.  

   Figure 2

1.       Navigate to the Views\Shared folder and select Site.Master.

2.       Click the OK button to add this view content page to the project.

b.      Add visual elements to the View

                                                               i.      If it is not already open, open the Details view by double-clicking List.aspx in the Solution Explorer.  Click the Source tab at the bottom of the editor.

                                                             ii.      Replace the code in Details.aspx with the following

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Details.aspx.cs" Inherits="TestMVC.Views.Customers.Details" %>

<%@ Import Namespace="TestMVC.Views.Customers"%>

<%@ Import Namespace="TestMVC.Models" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

    <div>

        CustID:

        <%=((Customer)ViewData.Model).CustID %><br />

        Name:

        <%=((Customer)ViewData.Model).FirstName %>

        <%=((Customer)ViewData.Model).LastName %>

        <br />

        Address:

        <%=((Customer)ViewData.Model).StreetAddress%><br />

        City:

        <%=((Customer)ViewData.Model).City %><br />

        State:

        <%=((Customer)ViewData.Model).State %><br />

        ZIP:

        <%=((Customer)ViewData.Model).PostalCode%><br />

    </div>

 

</asp:Content>


The above code displays details of a single Customer model object. 

4.       Modify the List view

a.       Open Views\Customers\List.aspx by double-clicking it in Solution Explorer.

b.      Find the <td>&nbsp;<\td> cell tag following the cust.PostalCode cell.  Replace this with the following code.  This generates a hyperlink displaying the text “Details”.  The URL of the hyperlink will have the current controller (“Customer”) the “Details” Action and the ID of the current customer.

<td>

<%=Html.ActionLink("Details", "Details", new { ID=cust.CustID})%>

</td>

5.       Test the application

a.       Save and compile the solution (Build | Build Solution).   Correct any errors you find.

b.  Run the solution (Debug | Start Debugging).  Depending on the port number used by Casini, it should display in your browser with a URL such as
http://localhost:4152/Home

c.       Navigate to the List page by changing the URL to
http://localhost:4152/Customers/List
(Replace the port number if necessary)

d.      You should see a list of 2 customers in your browser.  Each customer should have a hyperlink labeled “Details”. 

    Figure 3

e.      Click the hyperlink next to customer 1.  The URL should change to
http://localhost:4152/Customers/Details/1
and the details of the first customer should display on screen.

    Figure 4

f.        Set a breakpoint in the Details method of CustomerController.cs and refresh the page to step through the code as it executes.

In this article, we added a view and controller to our application and used these to retrieve and display customer details by the Customer ID. 

.Net | ASP.NET | MVC
Wednesday, August 27, 2008 1:26:29 PM (GMT Daylight Time, UTC+01:00)
# Friday, August 22, 2008

Microsoft recently released the ASP.Net Model View Controller framework (MVC).  It is currently available as Preview 3 and can be downloaded at http://www.microsoft.com/downloads/details.aspx?FamilyId=92F2A8F0-9243-4697-8F9A-FCF6BC9F66AB&displaylang=en

A new MVC project contains a couple sample views and controllers so you can get an idea of the proper syntax to use. 

In this article, we will add a new model, view and controller to an existing MVC project. 

1.       Open Visual Studio 2008 and create a new MVC project.  For information on how to create a new MVC project, see http://www.davidgiard.com/2008/08/18/TheASPNetMVCSampleAppDemystified.aspx

2.       Open the Solution Explorer (View | Solution Explorer) and select the Models folder.

3.       Add a Model to the project

a.       Right-click the Models folder and select Add | Class.  The Add New Item dialog displays.
Figure 1
    Figure 1

                                                               i.      At the Name textbox, enter “Customer”.

                                                             ii.      Click the OK button to create a Customer class.

b.      The Customer class opens in the class editor.  This class will contain a few public properties that help describe a customer object.  Add the following code to the Customer class.

    public class Customer

    {

        public int CustID { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string StreetAddress { get; set; }

        public string City { get; set; }

        public string State { get; set; }

        public string PostalCode { get; set; }

    }

4.       Add a Controller to the project

a.       In the Solution Explorer, right-click the Controllers folder and select Add | New Item.  The Add New Item dialog displays.
Figure 2
    Figure 2

                                                               i.      Under Categories, select Visual C#\Web\MVC.

                                                             ii.      Under Templates, select MVC Controller Class.

                                                            iii.      In the Name textbox, enter “CustomerController”.

                                                           iv.      Click the Add button to create the CustomerController class and open it in the class editor.

b.      In the CustomerController class, we will create some actions.  Each action will instantiate one or more Model objects and display them in a view object. 

                                                               i.      Add the following statement at the top of the CustomerController class. 

using TestMVC.Models;

                                                             ii.      Add the following private methods to the CustomerController class.  For now, we will create customers out of thin air (as if it were that easy).  In a real application, we would probably call a web server or query a database to get customers.

        #region private methods

        private Customer GetCustomer1()

        {

            var cust1 = new Customer

            {

                CustID = 1,

                FirstName = "David",

                LastName = "Giard",

                StreetAddress = "123 Main",

                City = "Boringville",

                State = "MI",

                PostalCode = "48108"

            };

 

            return cust1;

        }

 

        private Customer GetCustomer2()

        {

            var cust2 = new Customer

            {

                CustID = 2,

                FirstName = "John",

                LastName = "Smith",

                StreetAddress = "321 Elm",

                City = "Nowhere",

                State = "OH",

                PostalCode = "41001"

            };

 

            return cust2;

        }

 

        private List<Customer> GetAllCustomers()

        {

            Customer cust1 = GetCustomer1();

            Customer cust2 = GetCustomer2();

            List<Customer> allCusts = new List<Customer> {cust1, cust2};

            return allCusts;

        }

 

        #endregion

                                                            iii.      Add some Action method to the CustomerController class.  We’ll start with a List action.  Paste the following code into CustomerController.cs.

        public ActionResult List()

        {

            var allCustomers = GetAllCustomers();

            return View("List", allCustomers);

        }

                                                           iv.      In the List, we get a list of customers (all 2 of them) and return a view.  Unlike the generated code, we explicitly specify which view to return (“List”) and we pass in some extra data (allCustomers) that the view will consume.

5.       Add a view to the project.

a.       In the Solution Explorer, right-click the Views folder and select Add | New Folder.  A new folder appears in the Solution Explorer.  Rename this folder to “Customer”.

b.      In the Solution Explorer, right-click the Customer folder and select Add | New Item.  The Add New Item dialog displays.

                                                               i.      Under Categories, select Visual C#\Web\MVC.

                                                             ii.      Under Templates, select  MVC View Content Page.

                                                            iii.      In the Name textbox, enter “List”.

                                                           iv.      The Select a Master Page dialog displays. 
Figure 3
   Figure 4

1.       Navigate to the Views\Shared folder and select Site.Master.

2.       Click the OK button to add this view content page to the project.

c.       Add visual elements to the View

                                                               i.      If it is not already open, open the List view by double-clicking List.aspx in the Solution Explorer.  Click the Source tab at the bottom of the editor.

                                                             ii.      Replace the code in List.aspx with the following

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="List.aspx.cs" Inherits="TestMVC.Views.Customers.List" %>

<%@ Import Namespace="TestMVC.Views.Customers"%>

<%@ Import Namespace="TestMVC.Models"%>

 

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

    <h2><%= Html.Encode(ViewData["Message"]) %></h2>

    <table>

        <tr>

            <td>ID</td>

            <td>First</td>

            <td>Last</td>

            <td>Addr</td>

            <td>City</td>

            <td>State</td>

            <td>ZIP</td>

            <td>&nbsp;</td>

        </tr>

        <% foreach (Customer cust in (List<Customer>)ViewData.Model)

           { %>

            <tr>

                <td><%=cust.CustID %></td>

                <td><%=cust.FirstName%></td>

                <td><%=cust.LastName%></td>

                <td><%=cust.StreetAddress%></td>

                <td><%=cust.City%></td>

                <td><%=cust.State%></td>

                <td><%=cust.PostalCode%></td>

                <td>&nbsp;</td>

            </tr>

        <% } %>

    </table>

</asp:Content>


The above code displays a list of Customer model objects.  In a real-world example, we may choose to have the Customer model derive from a base class and only refer to the base class in the view.  This would increase the separation between our view and our model.

6.       Test the application

a.       Save and compile the solution (Build | Build Solution).   Correct any errors you find.

b.  Run the solution (Debug | Start Debugging).  Depending on the port number used by Casini, it should display in your browser with a URL such as
http://localhost:4152/Home

c.       Navigate to the List page by changing the URL to
http://localhost:4152/Customers/List
(Replace the port number if necessary)

d.      You should see a list of 2 customers in your browser
Figure 4
    Figure 4

e.      Set a breakpoint in the List method of CustomerController.cs and refresh the page to step through the code as it executes.

In this article, we created a model, view and controller from scratch and displayed them.  You can download the code for this project here.

In the next article, we will use the ID of the URL to specify a single customer.

.Net | ASP.NET | MVC
Friday, August 22, 2008 2:02:34 PM (GMT Daylight Time, UTC+01:00)
# Monday, August 18, 2008

Microsoft recently released the ASP.Net Model View Controller framework (ASP.Net MVC).  It is currently available as Community Technology Preview 3 and can be downloaded at http://www.microsoft.com/downloads/details.aspx?FamilyId=92F2A8F0-9243-4697-8F9A-FCF6BC9F66AB&displaylang=en

This article describes how to create an ASP.Net MVC application and the code that is auto-generated for you.

Creating a new ASP.Net MVC project

1.       Open Visual Studio 2008.  Create a new project: Select File | New Project.  The New Project dialog displays.

    Figure 1

a.       Under Project Type, select Visual Basic\Web or Visual C#\Web, depending on your language preference.

b.      Under Templates, select ASP.Net MVC Web Application.  This application was added when you installed the ASP.Net MVC preview.

c.       Provide an appropriate location and name for the project and solution.

d.      Click the OK button to create the project.

2.       One of the advantages of an ASP.Net MVC project is that the separation of most of the code from the user interface makes it easier to write unit tests.  Visual Studio encourages you to create unit tests for your new project by prompting you with the Create Unit Test Project dialog every time you create an MVC project.

    Figure 2

a.       If you wish, you can decline to create a Unit Test project or you can change the default project name.  Typically I do not change any defaults on this dialog.

b.      Click the OK button to create the Unit Test project.

The Folder structure of an MVC project

When you create a new MVC project, Visual Studio, generates a couple views and controllers.  If you understand how these work, you can use them to guide how you will create more views and controllers.

The solution contains two projects: an MVC project and a unit test project.

View the projects in Solution Explorer.  Select View | Solution Explorer.  The MVC project contains several folders.


    Figure 3

1.       The Content folder contains a stylesheet Site.css for this site.

2.       The Controllers folder is where you will store all your controller classes.  By default, this folder contains a single controller class - HomeController.cs.

3.       The Models folder is where you will store any model classes for your application.

4.       The Views folder contains a subfolder for each view in your application.  By default, there are two subfolders: Home and Shared. 

a.       The Shared subfolder contains a master page for the site because it is shared by multiple web pages.  Any other UI elements shared by the site belong in this folder.

b.      The Home folder contains two pages: About.aspx and Index.aspx. 

5.       As with most web applications, the root folder of this project contains a Global.asax file and a Web.Config file, which contain setup and configuration information for the application as a whole.

The Files and Folders of an MVC project

Open Global.asax and view the code.  Notice that the Application_Start method (which fires once, at the startup of the web application) contains a call to the RegisterRoutes method. The RegisterRoutes method tells the MVC framework how to interpret a URL. 

public static void RegisterRoutes(RouteCollection routes)

{

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 

    routes.MapRoute(

        "Default",                                              // Route name

        "{controller}/{action}/{id}",                           // URL with parameters

        new { controller = "Home", action = "Index", id = "" }  // Parameter defaults

    );

 

}

The routes.MapRoute method accomplishes this.  In this case, a “Default” route collection is created that interprets a URL with syntax like “{controller}/{action}/{id}”. 

·         The first part of the URL specifies the controller to use.  MVC looks in the Controllers folder for a class that inherits from System.Web.Mvc.Controller with a name that matches the controller specified in the URL.

·         The second part of the URL specifies the action to take.  The action is the public method within this controller that will be called. 

·         The third part of the URL specifies an id to pass to the action method.  This can be used to further customize the action.  For example, we could use the id as a filter to dynamically look up a single row in a database.

The routes.MapRoute method also allows us to specify defaults if no controller or action or id is specified in the URL.  If any of these are omitted from the URL, MVC will use the defaults specified in the third parameter of routes.Maproute.  In this case the object new { controller = "Home", action = "Index", id = "" } tells MVC the following:

·         If no Controller is specified in the URL, assume the Home controller (i.e., look for a class named “Home.cs” in the Controllers folder).

·         If no Action is specified in the URL, assume the Index action (i.e., look for a public method “Index” in the Home.cs class).

·         If no ID is specified in the URL, assume a blank ID (i.e., any code looking for an ID will retrieve an empty string).

Open the view files: Home.aspx and About.aspx and notice that there is no code behind in either.  This is because ASP.Net MVC applications do not execute the page life cycle.  All the code for this application is in the controllers.  These view pages contain only visual elements.

Open the controller class: Homecontroller.cs.  As we mentioned before, this class derives from the System.Web.Mvc.Controller class and it contains two methods: Index and About.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace TestMVC.Controllers

{

    public class HomeController : Controller

    {

        public ActionResult Index()

        {

            ViewData["Title"] = "Home Page";

            ViewData["Message"] = "Welcome to ASP.NET MVC!";

 

            return View();

        }

 

        public ActionResult About()

        {

            ViewData["Title"] = "About Page";

 

            return View();

        }

    }

}

“HomeController” is the name of the class to implement the Home controller.  This is typical of how MVC works – developers follow naming conventions in order tell the framework where to find the code to run.  In the case of controllers, we implement a controller by sub-classing the System.Web.Mvc.Controller class, naming this subclass “xxxController” (where xxx is the Controller name) and placing that subclass in the Controllers folder of our MVC project.  If we wanted to call a controller named “David”, we would create a System.Web.Mvc.Controller class named “DavidController” into the Controllers folder.  This process is known as “convention over configuration”, meaning that the framework knows where to find code based on the names we use.

Let’s look closely at the Index method.  Recall that the method in the controller is the Action that is specified in the URL.  So the Index method will be called if the Index action is specified.

ViewData is a dictionary collection that is a property of every Controller object.  We can add or update items in this collection by syntax such as
ViewData["Title"] = "Home Page";

By placing items in this collection, we make them available to the view when it is called.

The view (remember this is the UI that the user will see) is returned from this method.  The following line returns the default view.
return View();

We know it is the default view because the statement did not specify the name of the view.  The default view has the same name as the Action called.  In this case, we are returning the Index view.  Once again, MVC uses conventions to determine where to find the view.  All views associated with a given controller are stored in a subfolder named for that controller beneath the Views folder.  In this case, we are using the Home controller, so we look for views in the Views\Home folder of the project.  The view itself is a file with the same name as the view and with an extension of “.aspx” or “.ascx”.  In this case, we are looking for the default view (Index) of the Home controller.  MVC renders the page Views\Home\Index.aspx for this view.  Again, the developer uses naming conventions to tell the framework where to find items.

Open Index.aspx.  Notice it displays the message stored in the ViewData dictionary by the controller.
<%
= Html.Encode(ViewData["Message"]) %>

However, it contains no other code, because all logic is handled by the controller.

Conclusion

Creating a new ASP.Net MVC project is as easy as creating any other Visual Studio project.  Learning the paradigm that the MVC framework uses can be a challenge; but the samples created automatically with a new project can ease that learning curve.

In the next article, we will add a new controller and view to a project.

.Net | ASP.NET | MVC
Monday, August 18, 2008 4:37:58 PM (GMT Daylight Time, UTC+01:00)
# Sunday, August 17, 2008

The Model-View-Controller (MVC) design pattern has existed for years.  (http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html)  ASP.Net developers have been implementing it for years either through their own custom code or via third-party frameworks such as Monorail (http://www.castleproject.org/monorail/index.html).

Recently, Microsoft released the ASP.Net MVC framework to give web developers the option of using this design pattern without the need for a lot of “plumbing” code or the use of a third-party framework.

The Model-View-Controller design pattern splits an application into three distinct parts called (you guessed it) “Models”, “Views” and “Controllers”. 

A Model represents the stateful data in an application.  These are often represented as objects such as “Customer” and “Employee” that represent an abstract business object.  For persistent data, the Model may save and retrieve data to and from a database.  Public properties of these objects (for example, “LastName” or “HireDate”) represent their state at any give time.  The model objects have no visual representation and no knowledge of how they will be displayed on screen. 

A View is the application’s user interface (UI).  In a web application, this is the web page that the user sees and clicks and interacts with directly.  The View can display data but it has no knowledge of where the data it displays comes from.

A Controller is the brains of your application.  It links the Model to the View.  It handles communication between the other two parts of the application.  It is smart enough to detect when a data needs to be retrieved (from the model) and refreshed (in the view).  It sends updated data from the view back to the model so that the model can persist it. 

Below is Trygve M. H. Reenskaug’s diagram of the relationship between these thee parts.

    Figure 1

This separation of the various concerns of the application encourages developers to create loosely-coupled components.

Much of the communication to the controller occurs by raising events in the view, which keeps the controller loosely coupled from the other parts.  However the real advantage of the MVC pattern is that, because they only communicate through the controller, the model and view are very loosely coupled.  This provides the following advantages to an MVC application.

  • Loosely-coupled applications have fewer dependencies, making it easier to switch the user interface or backend at a later time.
  • Applications can be tested more easily, because so little code is in the view.  We can test our code by writing unit tests against the controller.

In the next article, we will look at how to create a Microsoft ASP.Net MVC application.

.Net | ASP.NET | MVC
Sunday, August 17, 2008 2:03:21 PM (GMT Daylight Time, UTC+01:00)
# Thursday, June 26, 2008

Binding to a GridView

ASP.Net data binding is a great technology for developers who want to create interactive web applications without writing a lot of code. For example, a developer can drop a GridView and a DataObject onto a web form, set a few properties and have a fully editable grid, allowing users to easily view and update data. 

Even sorting the grid data can be performed without writing any code.  Just set the GridView's AllowSorting property to "true" and set the SortExpression property of any "sortable" column. 

<asp:GridView
   ID="GridView1"
   runat="server"
   AllowSorting="true"

...

   <asp:BoundField
      DataField="Name"
      HeaderText="Product Name"
      SortExpression="Name" />

...

By default, the grid renders a link at the top of each sortable column.  Clicking this link toggles the sort order between 3 states: Ascending, Descending and No Sort. 


Sorting Limitations

But there is a "Gotcha".  The GridView can be bound to any set of data - that is, to any object that implements the System.Collections.IEnumerable interface.  This includes a DataTable, ArrayList, List and HashTable, among others.  However the automatic sorting only works when binding to a DataTable.

Personally, I prefer to work with and bind to generic Lists.  A List is more flexible than a DataTable and does a better job of abstracting the user interface from the back-end data source, making it easier to swap out one or the other.

But by binding to a List, I sacrifice the automatic sorting that happens when I bind to a DataTable.  Fortunately, it doesn't take a lot of code to implement sorting on a GridView bound to a generic List.

How to sort a GridView bound to a List

First, we set the GridView AllowSorting property and each column's SortExpression property as described above.  This provides "sort" links at the top of each column.  Unfortunately these links will not work properly - in fact, clicking them will generate an error.

To get this to work, you must do the following

  1. Add an extra "sortby" parameter of type string to your Select method.
  2. Add code to your sort method to sort the list before returning it (more on this later)
  3. Add a SortParameterName attribute to your ObjectDataSource.  The value of this parameter should be the same as the parameter you added to your Select method.

By setting the SortParameterName attribute, we are telling ASP.Net to pass sorting information to the Select method and which parameter to pass it to.  The Select method gets called when the grid loads or refreshes and whenever the user clicks the "sort" links at the top of each column.  Most of the time, the value passed to the sortby parameter is an empty string (indicating no sort order), but if the user clicks a "sort" link, this parameter will contain one of the following three values

  • "<SortField> ASC"
  • "<SortField> DESC"
  • ""

where <SortField> is the string specified in the SortExpression attribute of the column clicked.  With each click, the grid column cycles its sort between ascending order, descending order, and no sort.  The parameter value passed depends on which is currently the active sort. 


<asp:ObjectDataSource ID="ProductObjectDataSource" runat="server" 
      SelectMethod="GetProductsList"
      TypeName="DemoGridBusLayer.NWindBL"
      SortParameterName="sortBy">
</asp:ObjectDataSource>

Now, how do we sort a List?  More specifically, how do we sort a list when we don't know in advance on which column we are sorting or in which direction (ascending or descending)? 

A List has a Sort method, so we can call that.  But what does it mean to sort a list of objects?  An object has properties and we can sort on any one (or more) of those properties, as long as the property is of a type that can be sorted.  We need to specify on which object property we will be sorting.  To do this, we use an overload of the List.Sort method that accepts an IComparer object.  IComparer has a Compare method that tells the Sort method how to order each pair of objects in the list.  We can create a class that implements IComparer, override the Compare method and use reflection to determine at runtime on which property to sort.  The name of the property and the sort order (Ascending or Descending) can be passed into the class constructor. 

The code for this class (named GenericComparer) below:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Reflection;

namespace DemoGridBusLayer
{
    /// <summary>
    /// This class is used to compare any
    /// type(property) of a class for sorting.
    /// This class automatically fetches the
    /// type of the property and compares.
    /// </summary>
    public sealed class GenericComparer<T> : IComparer<T>
    {
        public enum SortOrder { Ascending, Descending };

        #region Constructors
        public GenericComparer(string sortColumn, SortOrder sortingOrder)
        {
            this._sortColumn = sortColumn;
            this._sortingOrder = sortingOrder;
        }

        /// <summary>
        /// Constructor when passing in a sort expression containing both the Sort Column and the Sort Order
        /// e.g., "BPCode ASC".
        /// </summary>
        /// <param name="sortExpression"></param>
        /// <remarks>
        /// This constructor is useful when using this with the ASP.NET ObjectDataSource,
        /// which passes the SortParameterName in this format
        /// </remarks>
        public GenericComparer(string sortExpression)
        {
            string[] sortExprArray = sortExpression.Split(" ".ToCharArray());
            string sortColumn = sortExprArray[0];
            SortOrder sortingOrder;
            sortingOrder = SortOrder.Ascending;
            if (sortExprArray.Length > 1)
            {
                if (sortExprArray[1].ToUpper() == "DESC")
                {
                    sortingOrder = SortOrder.Descending;
                }
            }

            this._sortColumn = sortColumn;
            this._sortingOrder = sortingOrder;
        }

        #endregion



        #region public properties
        /// <summary>
        /// Column Name(public property of the class) to be sorted.
        /// </summary>
        private string _sortColumn;
        public string SortColumn
        {
            get { return _sortColumn; }
        }

        /// <summary>
        /// Sorting order (ASC OR DESC)
        /// </summary>
        private SortOrder _sortingOrder;
        public SortOrder SortingOrder
        {
            get { return _sortingOrder; }
        }

        #endregion

        /// <summary>
        /// Compare two objects of the same class,
        /// based on the value of a given property
        /// </summary>
        /// <param name="x">First Object</param>
        /// <param name="y">Second Object</param>
        /// <returns>int</returns>
        public int Compare(T x, T y)
        {

            // User reflection to get the property
            PropertyInfo propertyInfo = typeof(T).GetProperty(_sortColumn);

            // Cast the property to IComparable, so we can use the built-in compare.
            IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null);
            IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null);

            // Order depends on Asc vs Desc.
            if (_sortingOrder == SortOrder.Ascending)
            {
                return (obj1.CompareTo(obj2));
            }
            else
            {
                return (obj2.CompareTo(obj1));
            }
        }
    }
}


Within our select method, we can call the List's Sort method and pass in an instance of the GenericComparer class, specifying on which column and in which direction to sort the list.  The SelectMethod is shown below.  (The details of querying a database and storing results into a List of objects is omitted.)

        /// <summary>
        /// Get a sorted list of all products
        /// </summary>
        /// <param name="sortBy"></param>
        /// <returns></returns>
        public static List<Product> GetProductsList(string sortBy)
        {
            // Get a list of Business Processes
            List<Product> prodList = GetProductsList();

            // Sort list
            if (sortBy != "")
            {
                GenericComparer<Product> cmp = new GenericComparer<Product>(sortBy);
                prodList.Sort(cmp);
            }
            return prodList;

        }

    }
}

With a small amount of code, we can enable sorting of a List of objects bound to a GridView in the same way that sorting is enabled for a DataTable bound to a GridView.

Demo

You can download the entire sample described in this article here: DemoGridSort.zip (39.63 KB).  You will need the AdventureWorks sample SQL Server database for this demo.

Thursday, June 26, 2008 5:05:33 PM (GMT Daylight Time, UTC+01:00)
# Tuesday, June 24, 2008

Did you know that every time an Ajax control performs a partial postpack, every event in the life cycle of the control's containing page or pages fires?

To me, this seems counterintuitive - There is no refresh of the containing page or of the master page, yet the Page_Load of both events fire.

I ran into it when I witnessed some unexpected behavior in a colleague's Ajax control.  After some investigation I saw the behavior was caused by code in the Page_Load event handler.  I thought this was a bug until I learned it was by design.  So we ended up bracketing some of the Page_Load code, testing the value of Page.IsPostBack to prevent code from running when it should not.

Tuesday, June 24, 2008 3:51:57 PM (GMT Daylight Time, UTC+01:00)
# Thursday, February 21, 2008

Scott Mitchell has an excellent article on 4GuysFromRolla.com about how to use ASP.Net to prompt a user to save changes before leaving a page.  It is part of a series he wrote back in 2004 but it is still relevant today.  The only change you should make today is that he calls methods of the Page class (IsStartupScriptRegistered, RegisterClientScriptBlock, RegisterArrayDeclaration) and these methods are depcrecated and replaced by the same methods in the Page.ClientScript class.

Scott's code initializes a client-side array with a list of inputs to monitor and the initial value of each input.  He then uses the onbeforeunload event to check if the data in any of these inputs has changed and displays a confirmation prompt if any data hase changed.  This event fires even if the user attempts to exit the form by closing the browser or clicking the brower's 'Back' button.

I liked Scott's approach so much that I took his public methods and moved them into a base class that inherits from System.Web.UI.Page and I inherit all my web pages from this class.  Now in each Page_Load, I can call methods of the base class to register controls that, if changed, will mark page data as dirty and prompt the user when he attempts to navigate away without saving.

I noticed that the "initial state" of controls were reset whenever a postback occurred, so I created a method "MarkDataAsDirty" that could be called when a control's "autopostback" fired but when the user is not finished entering data.  This sets a hidden form on the client that is checked in the onbeforeunload method to determine if data has changed.

I also made the methods public so they could be accessible to any user controls dropped on a page.  And I created the utility method RegisterForConfirmUnsavedChanges that registers the most common controls on the page using Scott's original methods.

I've included a sample ASP.NET web site in which every page inherits from a base page and methods of that base class are called to implement this functionality.

 

ConfirmSaveSite1.zip (9.51 KB)
Thursday, February 21, 2008 4:15:33 PM (GMT Standard Time, UTC+00:00)