ASP.NET MVC QuickStart 8: partial updates using jquery

Objectives

In this Hands-On Lab, you will learn how to do partial updates in JSON format using jquery. In particular, you will:
- Task 1: add new controller action and view
- Task 2: add controller action method to get list of members
- Task 3: add jquery to populate members combo box
- Task 4: show member details

System requirements

You must have the following items to complete this lab:
- Microsoft Visual Studio 2008 SP1 (professional edition)
- Microsoft ASP.NET MVC 1.0

Prequisites

You must have the following skills to understand this lab:
- Fundamental knowledge of software development in .NET 3.5
- Some experience in ASP.NET web development
This lab builds further on the QuickStart 7 code.

Task 1: add new controller action and view

We are going to create a new page that has a combo box containing all member last names, and the details of the selected member. First add a new controller action to the MembersController:

  1: public ActionResult Index2()
  2: {
  3:     // return this list to the default view
  4:     return View();
  5: }

Also add a view for this action method:

ASPNETMVC_QS8_01

In this case we are not going to create a strongly typed view because the needed data will be retrieved asynchronously using jquery.

Modify the generated view. First, place a combo box in the view:

  1: <%@ Page Title="" Language="C#"
  2:          MasterPageFile="~/Views/Shared/Site.Master"                                                  
  3:          Inherits="System.Web.Mvc.ViewPage" %>
  4: <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"
  5:              runat="server">
  6:   Index2
  7: </asp:Content>
  8: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
  9:              runat="server">
 10:     <h2>Index2</h2>
 11: 
 12:     <% <select id="MembersDropDownList" />
 13: </asp:Content>

To fill this combo box with members using AJAX, we have to:

  • Add a controller action method that returns a list of members
  • Write some jquery that uses the controller action method to populate the combo box when the page has been rendered

We will do this in the next tasks.

Task 2: add controller action method to get list of members

Add a new action method called GetCustomers to the MembersController:

  1:  public JsonResult GetMembers()
  2: {
  3:     // Get a list of members using the model
  4:     List<Member> members = MemberService.GetMembers();
  5: 
  6:     // Return list of members as JSON
  7:     return this.Json(members);
  8: }

As you see this method returns a different type of action result: a JsonResult. It’s in JSON format, which is a lightweight data-interchange format (see http://json.org).

Task 3: add jquery to populate members combo box

Now we have to consume the JSON data and populate the combo box with members.

First we need references to the jquery javascript libraries, so open up the Site.Master and add the needed references:

  1: <head runat="server">
  2:   <title>
  3:     <asp:ContentPlaceHolder ID="TitleContent" runat="server" />
  4:   </title>
  5:   <link href="../../Content/Site.css" rel="stylesheet"
  6:         type="text/css" />
  7:   <script src="/Scripts/jQuery-1.3.2.js"
  8:           type="text/javascript"></script>
  9:   <script src="/Scripts/jquery-1.3.2.min.js"
 10:           type="text/javascript"></script>
 11: </head>

Open the Index2 view. To retrieve the list of members when the DOM of the page is loaded and to populate the combo box with these members, we can write the following  jquery:

  1: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
  2:              runat="server">
  3:     <script type="text/javascript">
  4:         $(document).ready(function()
  5:         {       
  6:             // if the DOM is loaded, start retrieving the members
  7:             $.getJSON(
  8:                 "/Members/GetMembers", null, function(data)
  9:                 {
 10:                     addMembers(data);
 11:                 })       
 12:         });
 13:         function addMembers(data)
 14:         {
 15:             // Get the DOM reference to the drop-down list.        
 16:             var membersDropDownList = $("#MembersDropDownList");
 17: 
 18:             // Loop through each member and populate the combo box.           
 19:             $.each(data, function(index, optionData) {
 20:                 membersDropDownList.append("<option value='"
 21:                     + optionData.ID
 22:                     + "'>" + optionData. LastName                                               
 23:                     + "</option>");
 24:             });       
 25:         };
 26:     </script>
 27:     <h2>Index2</h2>
 28: 
 29:     <select id="MembersDropDownList" />
 30: 
 31: </asp:Content>

Take your time to study and understand the jquery syntax.

Now start the application and go to the page “/members/index2”. If everything works, the combo box should be populated:

ASPNETMVC_QS8_02

Task 4: show member details

Finally, we want to show the details of the selected member. The first step to do that is to provide a new action member for the MemberController that retrieves the details of a member. So add the following action method to the MemberController:

  1: public JsonResult GetMemberDetails(int memberID)
  2: {  
  3:     // Get member details using model
  4:     Member m = MemberService.GetMember(memberID);
  5:     // Return list of members as JSON
  6:     return this.Json(m);
  7: }

The next thing is to make sure that when the selected combo box item changes, the member details are updated. Again, we will do that with jquery:

  1: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
  2:              runat="server">
  3:     <script type="text/javascript">
  4:         $(document).ready(function()
  5:         {       
  6:             $.getJSON(
  7:                 "/Members/GetMembers", null, function(data)
  8:                 {
  9:                     addMembers(data);
 10:                 })
 11: 
 12:             var membersDropDownList = $("#MembersDropDownList");
 13:             membersDropDownList.change(function() {                                
 14:                 populateDetails(this.value);
 15:             })
 16:         });
 17:         function populateDetails(id)
 18:         {
 19:             $.getJSON("/Members/GetMemberDetails",
 20:                 {memberID : id }, function(data) {                
 21:                     $("#FirstName").html(data.FirstName);
 22:                     $("#LastName").html(data.LastName);
 23:                 });
 24:         }
 25:         function addMembers(data)
 26:         {
 27:             // Get the DOM reference to the drop-down list.        
 28:             var membersDropDownList = $("#MembersDropDownList");
 29: 
 30:             // Loop through each member and populate the combo box.           
 31:             $.each(data, function(index, optionData) {
 32:                 membersDropDownList.append("<option value='"
 33:                     + optionData.ID
 34:                     + "'>" + optionData.LastName
 35:                     + "</option>");
 36:             });       
 37:         };
 38:     </script>
 39:     <h2>Index2</h2>   
 40: 
 41:     <select id="MembersDropDownList"></select>
 42: 
 43:     <p />
 44: 
 45:     <div>First name: <span id="FirstName"></span></div>
 46:     <div>Last name: <span id="LastName"></span></div>              
 47: </asp:Content>

Start the application again, go to the page “/members/index2” and select another member. The details should become visible:

ASPNETMVC_QS8_03

One thing left: when we initially load this page, the member details are not filled in. To solve that, just add the following line of code:

  1: <script type="text/javascript">
  2:         $(document).ready(function()
  3:         {       
  4:             $.getJSON(
  5:                 "/Members/GetMembers", null, function(data)
  6:                 {
  7:                     addMembers(data);
  8:                     populateDetails(membersDropDownList.val());
  9:                 })
 10: 
 11:             var membersDropDownList = $("#MembersDropDownList");
 12:             membersDropDownList.change(function() {                                
 13:                 populateDetails(this.value);
 14:             })                                                                  
 15:         });
 16: </script>
 17: 
If you try it now, the member details will be visible when the page is first loaded
May 7, 2010 02:14 by lustuyck
E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

ASP.NET MVC QuickStart 7: action filters

Objectives

In this Hands-On Lab, you will be introduced to the ASP.NET MVC framework. In particular, you will:

  • Task 1: understand action filters
  • Task 2: built-in action filters
  • Task 3: write a custom action filter

System requirements

You must have the following items to complete this lab:

  • Microsoft Visual Studio 2008 SP1 (professional edition)
  • Microsoft ASP.NET MVC 1.0

Prequisites

You must have the following skills to understand this lab:

  • Fundamental knowledge of software development in .NET 3.5
  • Some experience in ASP.NET web development

This lab builds further on the QuickStart 6 code.

Task 1: understand action filters

An action filter is behavior that can be attached to controllers and action methods. They inject extra logic in the request processing pipeline:

  • before and after an action method runs
  • before and after action results are executed
  • during exception handling

Action filters are very powerful if you want to inject general-purpose code that has to be reused all over the place, but implemented once, such as logging, authorization, caching and others.

The MVC framework knows about following filter types:

Filter type            Interface              When run                         Default implementation
Authorization filter   IAuthorizationFilter   Before running any other         AuthorizeAttribute
                                              filter or action method 
Action Filter          IActionFilter          Before and after an action       ActionFilterAttribute
                                              method is run 
Result Filter          IResultFilter          Before and after an action       ActionFilterAttribute
                                              result is executed 
Exception filter       IExceptionFilter       Handles exception thrown         HandleErrorAttribute
                                              by action filter, action
                                              result or action method 

Task 2: built-in action filters

ASP.NET MVC has a number of built in action filters. To use them, you just need to decorate the controller or action filter with a specific action filter attribute, for example:

  1: [Authorize()]
  2: [OutputCache(Duration=60)]
  3: public ActionResult Index()
  4: {
  5:    …
  6: }

In this particular example, we use the AuthorizeAttribute to specify that the Index action method can only be executed if the user is logged in. We have also decorated the action method Index with the OutputCacheAttribute, which will cache the output of the action method for a specific duration (60 seconds). These two action filters are filters that are already built-in into the ASP.NET MVC framework, but of course you can build your own action filters. Other built in action filters are: AcceptVerbs, Bind, HandleError, ModelBinder, NonAction and others.

Task 3: write a custom action filter

In this task we will create a custom action filter that logs the stages of a request to a controller action. To keep things simple, we will just write to the Visual Studio output window.

To start, add a new folder to the MvcApplication1 web application and call it ActionFilters. Right click this folder and select Add -> Class, and name it LogAttribute, and implement it with the following code:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Web;
  5: using System.Web.Mvc;
  6: using System.Web.Routing;
  7: using System.Diagnostics;
  8: namespace MvcApplication1.ActionFilters
  9: {
 10:     public class LogAttribute : ActionFilterAttribute,
 11:                     IActionFilter, IResultFilter, IExceptionFilter
 12:     {
 13:         #region IActionFilter Members
 14:         void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
 15:         {
 16:             Log("OnActionExecuted", filterContext.RouteData);
 17:         }
 18:         void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
 19:         {
 20:             Log("OnActionExecuting", filterContext.RouteData);
 21:         }
 22:         #endregion
 23:         #region IResultFilter Members
 24:         void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)
 25:         {
 26:             Log("OnResultExecuted", filterContext.RouteData);
 27:         }
 28:         void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext)
 29:         {
 30:             Log("OnResultExecuting", filterContext.RouteData);
 31:         }
 32:         #endregion
 33:         #region IExceptionFilter Members
 34:         public void OnException(ExceptionContext filterContext)
 35:         {
 36:             Log("OnException", filterContext.RouteData);
 37:         }
 38:         #endregion
 39:         #region Log
 40:         public static void Log(string message, RouteData routeData)
 41:         {
 42:             Trace.WriteLine(
 43:                 string.Format("{0}, controller = {1}, action = {2}",
 44:                 message,
 45:                 routeData.Values["controller"],
 46:                 routeData.Values["action"]));
 47:         }
 48:         #endregion
 49:     }
 50: }

This code is very straightforward, notice the following:

  • the LogAttribute class inherits from ActionFilterAttribute, which provides you with the default implementation.
  • the LogAttribute class implements three interfaces: IActionFilter, IResultFilter and IExceptionFilter.
  • In each interface method the filter context is passed, that can be used to determine information about the context of where the method was triggered (controller, action method…).

Then add the following using statement on top of the MembersController:

  1: using MvcApplication1.ActionFilters;

Now you can apply the Log action filter, for example, decorate the action method Index of the MembersController with it:

  1: [Log]
  2: public ActionResult Index()
  3: {
  4:     // Get a list of members using the model
  5:     List<Member> members = MemberService.GetMembers();
  6: 
  7:     // return this list to the default view
  8:     return View(members);
  9: }

Hit F5 to start the web application, go to http://localhost:3382/members and have a look at the output window in visual studio:

ASPNETMVC_QS7_01

As you see, the various steps in the pipeline have been written to the output window.

Note: if you would throw an exception in the Index action method, the OnException step would be executed too.

May 7, 2010 02:08 by lustuyck
E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

ASP.NET MVC QuickStart 6: automated testing

Objectives

In this Hands-On Lab, you will be introduced to the ASP.NET MVC framework. In particular, you will:

  • Task 1: add a unit test project
  • Task 2: Test model
  • Task 3: Test controller
  • Task 4: Test routing

System requirements

You must have the following items to complete this lab:

  • Microsoft Visual Studio 2008 SP1 (professional edition)
  • Microsoft ASP.NET MVC 1.0

Prequisites

You must have the following skills to understand this lab:

  • Fundamental knowledge of software development in .NET 3.5
  • Some experience in ASP.NET web development

This lab builds further on the QuickStart 5 code.

Task 1: add a unit test project

In previous QuickStarts we didn’t focus on testing, because the focus was on other aspects of ASP.NET MVC. But one of the biggest advantages of the MVC framework is that you can unit test everything. If you take the test-driven approach, you would first create your tests and then write the code to make those tests pass.

Let’s start off with adding a unit test project: right click the MvcApplication1 solution and select Add -> New project. Select Test Project in Test project types and fill in name and location:

ASPNETMVC_QS6_01

Click OK. A test project is now added to your solution:

ASPNETMVC_QS6_02

Delete the generated UnitTest1.cs file. Also add a reference to the MvcApplication1 project, and to:

  • System.Web.Mvc
  • System.Web.Abstractions
  • System.Data
  • System.Data.DataSetExtensions
  • System.Web
  • System.Web.Routing

You should test every aspect of you project, in this case this means that you should test:

  • Model (MemberService)
  • Controller action methods (MemberController)
  • Routing

Task 2: Test model

Right click the TestProject1 project and select Add -> New test:

ASPNETMVC_QS6_03

Select Unit Test and name it ModelTest.cs. Click OK. Add the following using statement on top of the ModelTest class:

  1: using MvcApplication1.Models;

Then add some unit tests, like:

  1: [TestMethod]
  2: public void Get_Members_Returns_List()
  3: {
  4:     var members = MemberService.GetMembers();
  5:     Assert.IsNotNull(members, "No members retrieved");
  6:     Assert.AreEqual(5, members.Count, "Got wrong number of members");
  7:     Assert.AreEqual("Geoffrey", members[0].FirstName);
  8:     Assert.AreEqual("Denver", members[0].LastName);
  9:     // ...
 10: }
 11: [TestMethod]
 12: public void Delete_Member_Workd()
 13: {
 14:     var members_before = MemberService.GetMembers();
 15:     MemberService.DeleteMember(members_before[0].ID);
 16:     var members_after = MemberService.GetMembers();
 17:     Assert.AreEqual(4, members_after.Count, "Member was not deleted");           
 18:     // ...
 19: }

Run these tests and make sure they pass.

Task 3: Test controller

Add a new unit test to the test project and call it MembersControllerTest. Add the following using statements on top:

  1: using MvcApplication1.Controllers;
  2: using MvcApplication1.Models;
  3: using System.Web.Mvc;

Add the following tests:

  1: [TestMethod]
  2: public void Index_Presents_Correct_Page_Of_Members()
  3: {
  4:     MembersController membersController = new MembersController();
  5:     ViewResult result = membersController.Index() as ViewResult;
  6:        
  7:     Assert.IsNotNull(result, "Didn't render view");
  8:     var members = (IList<Member>)result.ViewData.Model;
  9:     Assert.AreEqual(5, members.Count, "Got wrong number of members");
 10:     Assert.AreEqual("Geoffrey", members[0].FirstName);
 11:     Assert.AreEqual("Denver", members[0].LastName);
 12: }
 13: [TestMethod]
 14: public void Details_Presents_Correct_Page_Of_Member()
 15: {
 16:     MembersController membersController = new MembersController();
 17:     ViewResult result = membersController.Details(0) as ViewResult;
 18:     Assert.IsNotNull(result, "Didn't render view");
 19:     var member = ((Member)result.ViewData.Model);           
 20:     Assert.AreEqual("Geoffrey", member.FirstName);
 21:     Assert.AreEqual("Denver", member.LastName);
 22: }

Run these tests and make sure they pass.

Task 4: Test routing

To test routing, we have to mock the request context. To do so, the easiest way is to use a mocking framework, and in this case we will be using moq, which can be downloaded from http://code.google.com/p/moq. Then, from the unit test project, add a reference to Moq.dll.

Add a new unit test and call it InboundRoutingTests.cs. On top of this class, add the following using statements:

  1: using System.Web.Routing;
  2: using MvcApplication1;
  3: using System.Web;

Testing a specific route comes always down to the same:

  • registering the web application’s route collection
  • mocking the request context
  • get the mapped route based in the URL
  • test the mapped route to see if it matches expected values

So we’ll first add a method that accepts a URL and expected routing data values and tests whether the URL routing matches these expected values:

  1: private void TestRoute(string url, object expectedValues)
  2: {
  3:     // Arrange: Prepare the route collection and a mock request context
  4:     RouteCollection routes = new RouteCollection();
  5:     MvcApplication.RegisterRoutes(routes);
  6:     var mockHttpContext = new Moq.Mock<HttpContextBase>();
  7:     var mockRequest = new Moq.Mock<HttpRequestBase>();
  8:     mockHttpContext.Setup(x => x.Request).Returns(mockRequest.Object);
  9:     mockRequest.Setup(x =>
 10:             x.AppRelativeCurrentExecutionFilePath).Returns(url);
 11:     // Act: Get the mapped route
 12:     RouteData routeData = routes.GetRouteData(mockHttpContext.Object);
 13:     // Assert: Test the route values against expectations
 14:     Assert.IsNotNull(routeData);
 15:     var expectedDict = new RouteValueDictionary(expectedValues);
 16:     foreach (var expectedVal in expectedDict)
 17:     {
 18:         if (expectedVal.Value == null)
 19:             Assert.IsNull(routeData.Values[expectedVal.Key]);
 20:         else
 21:             Assert.AreEqual(expectedVal.Value.ToString(),
 22:                                      
 23:         routeData.Values[expectedVal.Key].ToString());
 24:     }
 25: }

And finally we can write unit tests to test different routes, for example:

  1: [TestMethod]
  2: public void Slash_Goes_To_All_Members_Page()
  3: {
  4:     TestRoute("~/", new
  5:     {
  6:         controller = "Home",
  7:         action = "Index",
  8:         id = (string)null,               
  9:     });
 10: }
 11: [TestMethod]
 12: public void Member2_Goes_To_Member2_Details_Page()
 13: {
 14:     TestRoute("~/member2", new
 15:     {
 16:         controller = "Members",
 17:         action = "Details",
 18:         id = 2,
 19:     });
 20: }

Run these tests and make sure they pass.

May 7, 2010 02:05 by lustuyck
E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

ASP.NET MVC QuickStart 5: routing

Objectives

In this Hands-On Lab, you will be introduced to the ASP.NET MVC framework. In particular, you will:

  • Task 1: Understand routing
  • Task 2: Add constraint
  • Task 3: Add new route
  • Task 4: Generate outgoing URL’s

System requirements

You must have the following items to complete this lab:

  • Microsoft Visual Studio 2008 SP1 (professional edition)
  • Microsoft ASP.NET MVC 1.0

Prequisites

You must have the following skills to understand this lab:

  • Fundamental knowledge of software development in .NET 3.5
  • Some experience in ASP.NET web development

This lab builds further on the QuickStart 4 code.

Task 1: understand routing

In ASP.NET MVC, a URL does not map to a file, but on an action method of a controller. This routing from URL to controller/action can be configured in the routing table, that is configured in the RegisterRoutes method of the Global.asax.cs file in the web application project, which defaults to:

  1: public static void RegisterRoutes(RouteCollection routes)
  2: {
  3:     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  4:     routes.MapRoute(
  5:         "Default",                              // Route name
  6:         "{controller}/{action}/{id}",           // URL with parameters
  7:         new { controller = "Home",
  8:               action = "Index",
  9:               id = "" }                         // Parameter defaults
 10:     );
 11: }

Note: the routing system not only maps incoming URL’S to the appropriate controller/action, but also constructs outgoing URLS!

Each route defines an URL pattern and how to handle requests for such URL’s. For the default route, this means:

URL                                 Maps to
/                                   controller = Home, action = Index, id = “”
/members                            controller = Members, action = Index, id = “”
/members/create                     controller = Members, action = Create, id = “”
/members/details/2                  controller = Members, action = Details, id = “2”

If you omit controller in the URL, it defaults to Home because we specified a parameter default for controller. If you omit action in the URL, it defaults to Index because we specified a parameter default for action.

When you define a route by using the MapRoute method, you can pass a number of parameters:

  • a route name, which is optional
  • the URL pattern, using parameters
  • default values: default value for each parameter (optional)
  • constraints: constraints for each parameter (optional)

Task 2: Add constraint

If you use http://localhost:3382/members/Details/2 then it will map to the Details action method of the MembersController, and member with ID 2 will be shown. This works, because ‘2’ will be mapped to the id parameter of the Details action method.

However, http://localhost:3382/members/Details/a also matches the URL pattern “{controller}/{action}/{id}” and so ‘a’ will be mapped to the id parameter. But, id is of type int, and so you will get the error:

ASPNETMVC_QS5_01

Obviously, we know that id should be a valid number, but the routing system doesn’t know that. To solve this, we can add a constraint to be sure that the mapping is only done when id is a valid number:

  1: routes.MapRoute(
  2:       "Default",                          // Route name
  3:       "{controller}/{action}/{id}",       // URL with parameters
  4:       new { controller = "Home",
  5:             action = "Index",
  6:             id = 0 },                     // Parameter defaults
  7:       new { id = @"\d{1,6}" }             // Constraints
  8: );

Now, if id is not according to the regular expression ‘\d{1,6}’ (numeric, 1 to 6 digits long) then the rule does not match and  the URL http://localhost:3382/members/Details/a isn’t mapped:

ASPNETMVC_QS5_02

Task 3: Add new route

Suppose we want the following URL to work:

URL                          Maps to
/member1                     controller = Members, action = Details, id = “1”
/member3                     controller = Members, action = Details, id = “3”

If you try that, obviously it does not match any URL pattern yet, so you’ll get an error:

ASPNETMVC_QS5_03

To make this work, add a new route to the global.asax.cs file (it has to be the first one):

  1: public static void RegisterRoutes(RouteCollection routes)
  2: {
  3:     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  4:     routes.MapRoute(
  5:       "",                                  // Route name
  6:       "member{id}",                        // URL with parameters
  7:       new { controller = "Members",
  8:             action = "Details",
  9:             id = 0 },                      // Parameter defaults
 10:       new { id = @"\d{1,6}" }              // Constraints
 11:             );
 12:     routes.MapRoute(
 13:       "Default",                           // Route name
 14:       "{controller}/{action}/{id}",        // URL with parameters
 15:       new { controller = "Home",
 16:       action = "Index",
 17:      id = 0 },                             // Parameter defaults
 18:      new { id = @"\d{1,6}" }               // Constraints
 19:             );                      
 20: }

Note: add routes in the correct order: from most specific to least specific!

Now try http://localhost:3382/member3:

ASPNETMVC_QS5_04

Task 4: Generate outgoing URL’s

Generating hyperlinks should never be done hardcoded, always use the built in helper methods like Html.ActionLink because they use the routing system to correctly build the URL.

In previous examples we already used Html.ActionLink to construct the links to view, create, edit and delete members, for example:

  1: <%= Html.ActionLink("Details", "Details", new { id = item.ID })%>

This generated the links as follows:

ASPNETMVC_QS5_05

However, in task 3 we added a new route to view the details of a member, so that URL’s in the form of http://localhost:3382/member3 work. After adding this route, the generated URL’s look different:

ASPNETMVC_QS5_06

This is because Html.ActionLink uses the routing configuration to construct the URL’s.

Note: If we would have constructed the links hard coded, changing routing configuration may have broken those links!

May 7, 2010 02:01 by lustuyck
E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

ASP.NET MVC QuickStart 4: implement validation

Objectives

In this Hands-On Lab, you will create functionality to add validation of members. In particular, you will:

  • Task 1: understand validation
  • Task 2: add convenience method to ModelState
  • Task 3: implement validation logic in model
  • Task 4: handle validation errors in controller

System requirements

You must have the following items to complete this lab:

  • Microsoft Visual Studio 2008 SP1 (professional edition)
  • Microsoft ASP.NET MVC 1.0

Prequisites

You must have the following skills to understand this lab:

  • Fundamental knowledge of software development in .NET 3.5
  • Some experience in ASP.NET web development

This lab builds further on the QuickStart 3 code.

Task 1: understand validation

At this moment, when the user enters an empty first name and/or last name, everything works. Of course, we know that these properties are mandatory, so we have to add some validation logic to make sure that the user can’t enter invalid information.

Due to the separation of concerns, it is straightforward that this validation checking has to be done in the model, and that the view is responsible for showing any validation messages to the user. So what should happen is that the controller uses the model to do validation and then it passes the error information to the view.

Now, how can the controller pass error information to the view? The way to do this is by registering the errors in ModelState, which is a temporary storage area. The steps are:

  • Controller asks model to do validation and if validation fails, it receives the list of validation errors from the model.
  • Controller registers the validation errors in ModelState, by calling the ModelState.AddModelError method for each error. This will add all errors to the ModelStateDictionary.
  • The view has access to this ModelStateDictionary and you can use Html helper methods to display the information:
    • Html.ValidationSummary: returns a list of validation errors.
    • Html.ValidationMessage: returns validation message for specific field.

Task 2: add convenience method to ModelState

The ModelState.AddModelError method only allows adding one validation error at a time, so first we will create an extension method called ModelState.AddModelErrors that allows us to add a collection of validation errors in one method call.

Right click the web project MvcApplication1, and select Add -> New folder, and call it Helpers. Then right click the Helpers folder and select Add -> Class, and call it ModelStateHelpers.cs. Write the extension method as follows:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Web;
  5: using MvcApplication1.Models;
  6: using System.Web.Mvc;
  7: namespace MvcApplication1.Helpers
  8: {
  9:     public static class ModelStateHelpers
 10:     {
 11:         public static void AddModelErrors(
 12:                      this ModelStateDictionary modelState,
 13:                      IEnumerable<RuleViolation> errors)
 14:         {
 15:             foreach (RuleViolation issue in errors)
 16:             {
 17:                 modelState.AddModelError(
 18:                          issue.PropertyName, issue.ErrorMessage);
 19:             }
 20:         }
 21:     }
 22: }

Task 3: implement validation logic in model

Now we will create the validation logic in our model.

First we will create a new class that can hold information (property name and related error message) about a validation error. Add a new class called RuleValidation to the Models folder:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Web;
  5: namespace MvcApplication1.Models
  6: {
  7:     public class RuleViolation
  8:     {
  9:         public string ErrorMessage { get; private set; }
 10:         public string PropertyName { get; private set; }
 11:         public RuleViolation(string errorMessage)
 12:         {
 13:             ErrorMessage = errorMessage;
 14:         }
 15:         public RuleViolation(string errorMessage, string propertyName)
 16:         {
 17:             ErrorMessage = errorMessage;
 18:             PropertyName = propertyName;
 19:         }
 20:     }
 21: }

A very convenient way of telling whether there were validation errors is by throwing exceptions. So add a new class called RuleException to the Models folder, which is a special kind of exception that will hold all validation errors that have occurred:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Web;
  5: using System.Collections.Specialized;
  6: namespace MvcApplication1.Models
  7: {
  8:     public class RuleException : Exception
  9:     {
 10:         public IEnumerable<RuleViolation>
 11:                      RuleViolations { get; private set; }
 12:         public RuleException(IEnumerable<RuleViolation> ruleViolations)
 13:         {
 14:             RuleViolations = ruleViolations;
 15:         }       
 16:     }   
 17: }

Now it’s time to do the actual validation. Add the following two methods to the Member class in the Models folder:

  1: public bool IsValid
  2: {
  3:     get { return (GetRuleViolations().Count() == 0); }
  4: }
  5: public IEnumerable<RuleViolation> GetRuleViolations()
  6: {
  7:     if (String.IsNullOrEmpty(FirstName))
  8:         yield return new RuleViolation(
  9:                     "First name is required", "FirstName");
 10:     if (String.IsNullOrEmpty(LastName))
 11:         yield return new RuleViolation(
 12:                     "Last name is required", "LastName");
 13:     yield break;
 14: }

To keep things simple we demand that first name and last name have to be filled in.

Finally, we have to apply these validation checks in the MemberService operations. Add the following code to the CreateMember method in MemberService class in the Models folder:

  1: public static void CreateMember(Member member)
  2: {
  3:     if (!member.IsValid)
  4:         throw new RuleException(member.GetRuleViolations());
  5:     // Set member id to next free id
  6:     member.ID = members.Max(m => m.ID) + 1;
  7:     // add member to collection
  8:     members.Add(member);
  9: }

And do the same in the UpdateMember method:

  1: public static void UpdateMember(Member member)
  2: {
  3:     if (!member.IsValid)
  4:         throw new RuleException(member.GetRuleViolations());
  5:     // Find member in collection
  6:     Member foundMember = members.Find(m => m.ID == member.ID);
  7:     // Update member
  8:     foundMember.FirstName = member.FirstName;
  9:     foundMember.LastName = member.LastName;
 10: }

So when a new member is added or updated, before the actual creation or update happens the member object is checked to see if it’s valid – if it isn’t, a RuleException is thrown to the caller (which is the controller) that has to handle it.

Task 4: handle validation errors in controller

Modify code of the Create action method in the MembersController class as follows:

  1: [AcceptVerbs(HttpVerbs.Post)]
  2: public ActionResult Create(Member member)
  3: {
  4:     try
  5:     {
  6:         // Use model to create this new member
  7:         MemberService.CreateMember(member);
  8:         // Redirect to Details action method and pass the new id
  9:         return RedirectToAction("Details", new { id = member.ID });
 10:     }
 11:     catch (RuleException ex)
 12:     {
 13:         ModelState.AddModelErrors(ex.RuleViolations);
 14:         return View(member);
 15:     }
 16: }

And do the same for the Update action method:

  1: [AcceptVerbs(HttpVerbs.Post)]
  2: public ActionResult Edit(Member member)
  3: {           
  4:     try
  5:     {
  6:         // Use model to create this new member
  7:         MemberService.CreateMember(member);
  8:         // Redirect to Details action method and pass the new id
  9:         return RedirectToAction("Details", new { id = member.ID });
 10:     }
 11:     catch (RuleException ex)
 12:     {
 13:         ModelState.AddModelErrors(ex.RuleViolations);
 14:         return View(member);
 15:     }
 16: }

Note: The method ModelState.AddModelErrors is the extension method that we wrote earlier, so in order to use it we also have to add a using statement on top of the MembersController class:

  1: using MvcApplication1.Helpers;

Right, let’s test this. Start the web application, and create a new member but don’t fill in last name:

ASPNETMVC_QS4_01

Click Create.

ASPNETMVC_QS4_02

The validation does its work and validation errors are displayed. But why does it also display the ‘A value is required’ message?

Actually, except for the manual validation messages that you add yourself, ASP.NET MVC also does its own validation checks on properties. There is a validation of all bound properties of a member object, which are FirstName, LastName but also… ID – because default, all properties of an object are bound to the view, even if this property is not used in the view. In our case, the ID is of type int, and therefore it cannot be null; so the validation message is added.

To solve this, we have to tell MVC not to bind the ID property, because it’s our responsibility to generate it. You can do this by decorating the Member class with the Bind attribute as follows:

  1: [Bind(Include = "FirstName,LastName")]
  2: public class Member
  3: {
  4:     public int ID { get; set; }
  5:     public string FirstName { get; set; }
  6:     public string LastName { get; set; }
  7:     …
  8: }

Now only FirstName and LastName properties are bound and validated; and so ID is not validated anymore:

ASPNETMVC_QS4_03

May 6, 2010 23:43 by lustuyck
E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

ASP.NET MVC QuickStart 3: Implement details, create, edit and delete functionality

Objectives

In this Hands-On Lab, you will create functionality to display the details of a member and add admin functionality to add, edit and delete members. In particular, you will:

  • Task 1: making the Details link work
  • Task 2: making the Create New link work
  • Task 3: making the Edit link work
  • Task 4: making the Delete link work
  • Task 5: adding validation

System requirements

You must have the following items to complete this lab:

  • Microsoft Visual Studio 2008 SP1 (professional edition)
  • Microsoft ASP.NET MVC 1.0

Prequisites

You must have the following skills to understand this lab:

  • Fundamental knowledge of software development in .NET 3.5
  • Some experience in ASP.NET web development

This lab builds further on the QuickStart 2 code.

Task 1: making the Details link work

When you click on the Details link, you would expect to see a page with the details of that specific member.

First, start the web application again and hover the Details links to see the URL each link refers to (generated by the Html.ActionLink methods):

ASPNETMVC_QS3_01

It’s interesting to see that these URL’s don’t use some exotic querystring to indicate the ID of the member; instead it’s a clean URL that is routed to the Details action method of the MembersController. So we’ll proceed by writing that action method to handle clicks on the Details links.

The first thing we need to do is to update our Model code so that we can retrieve the details of a member, because that’s the responsibility of the model. So open the MemberService class in the Model folder, and add the following method:

  1: public static Member GetMember(int id)
  2: {
  3:     return members.Find(m => m.ID == id);
  4: }

This simply uses a lambda expression to find the member with specified id in the members collection.

Now we will create the controller action: open the MembersController class in the Controllers folder and add the following method:

  1: public ActionResult Details(int id)
  2: {
  3:     // Get member details for the specified member id
  4:     Member member = MemberService.GetMember(id);
  5:     // return this member to the default view
  6:     return View(member);
  7: }

Finally we have to create the view that will show the member details. Right click the Details method and select Add View, and make sure everything is filled in as follows:

ASPNETMVC_QS3_02

Make sure that:

  • The View name is called Details.
  • You check the Create a strongly typed view check box, and set the View data class to MvcApplication1.Models.Member. This way, we will be able to access the member data in the view in a strongly typed way.
  • Select Details as the View content. This will generate code that displays the details of a member.

Click Add. As a result, a Details.aspx view is added to the Views/Members folder:

  1: <%@ Page Title="" Language="C#"
  2:          MasterPageFile="~/Views/Shared/Site.Master"
  3:          Inherits="System.Web.Mvc.ViewPage<
  4:                       MvcApplication1.Models.Member>" %>
  5: <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"
  6:              runat="server">
  7:  Details
  8: </asp:Content>
  9: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
 10:              runat="server">
 11:     <h2>Details</h2>
 12:     <fieldset>
 13:         <legend>Fields</legend>
 14:         <p>
 15:             ID:
 16:             <%= Html.Encode(Model.ID) %>
 17:         </p>
 18:         <p>
 19:             FirstName:
 20:             <%= Html.Encode(Model.FirstName) %>
 21:         </p>
 22:         <p>
 23:             LastName:
 24:             <%= Html.Encode(Model.LastName) %>
 25:         </p>
 26:     </fieldset>
 27:     <p>
 28:         <%=Html.ActionLink("Edit", "Edit", new
 29:                       { /* id=Model.PrimaryKey */ }) %> |
 30:         <%=Html.ActionLink("Back to List", "Index") %>
 31:     </p>
 32: </asp:Content>

And again,  replace the documented code in the action links so that we assign the primary key to each member instance for the Edit link:

  1: <%= Html.ActionLink("Edit", "Edit", new { id=Model.ID }) %> |

Put a breakpoint at the first line in the Details action method in the MembersController and hit F5 to debug the application. Change the url to http://localhost:3382/members/index and click on the Details link of a specific member. When the breakpoint hits, you can see that the id parameter of the action method equals the id of that specific member:

ASPNETMVC_QS3_03

Now how does the action method knows this id? This is because of model binding feature of ASP.NET MVC. Your action methods need data, and the incoming HTTP request carries the data it needs, which can be in the form of query string, posted form values and so on. So if you click such link, a new request is created containing the id; and the DefaultModelBinder automatically takes that member id out of the request and maps it to the id parameter of the action method. It can do so because both parameter name and action link value have the same name:

ASPNETMVC_QS3_04

So continue to debug the code to see how the correct member is retrieved using the MemberService,  and how the resulting member is passed to the default view. As a result, the Details view is rendered:

ASPNETMVC_QS3_05

Note: The Back To List link already works, because it was implemented for us:

  1: <%=Html.ActionLink("Back to List", "Index") %>

Task 2: making the Create New link work

First, update our Model code so that we can create a new member. Open the MemberService class in the Model folder, and add the following method:

  1: public static void CreateMember(Member member)
  2: {
  3:     // Set member id to next free id
  4:     member.ID = members.Max(m => m.ID) + 1;
  5:     // add member to collection
  6:     members.Add(member);
  7: }

This method takes care of adding a new member to the collection and making sure it gets a valid id.

Then, in the Index.aspx view in the Views/Members folder, the Create New link looks like:

  1: <%= Html.ActionLink("Create New", "Create") %>

The second parameter is the name of the action method, so this means that we have to create a new action method Create in the MembersController class (if we don’t specify the controller name explicitly, it will take the current one, which is fine in this case):

  1: public ActionResult Create()
  2: {
  3:     return View();
  4: }

If the Create New link is clicked, the Create action method of the MembersController will be executed, and in this method we just return the default view for creating new members. This view does not exist yet, so right click the Create action method and select Add View, and make sure everything is filled in as follows:

ASPNETMVC_QS3_06

Make sure that:

  • The View name is called Create.
  • You check the Create a strongly typed view check box, and set the View data class to MvcApplication1.Models.Member. This way, we will be able to access the member data in the view in a strongly typed way.
  • Select Create as the View content. This will generate code that displays the creation of a member.

Click Add and a new view called Create.aspx will be added to the Views/Members folder:

  1: <%@ Page Title="" Language="C#"
  2:          MasterPageFile="~/Views/Shared/Site.Master" 
  3:          Inherits="System.Web.Mvc.ViewPage<
  4:                           MvcApplication1.Models.Member>" %>
  5: <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"
  6:              runat="server">
  7:  Create
  8: </asp:Content>
  9: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
 10:              runat="server">
 11:     <h2>Create</h2>
 12:     <%= Html.ValidationSummary("Create was unsuccessful. Please correct
 13:                                 the errors and try again.") %>
 14:     <% using (Html.BeginForm()) {%>
 15:         <fieldset>
 16:             <legend>Fields</legend>
 17:             <p>
 18:                 <label for="ID">ID:</label>
 19:                 <%= Html.TextBox("ID") %>
 20:                 <%= Html.ValidationMessage("ID", "*") %>
 21:             </p>
 22:             <p>
 23:                 <label for="FirstName">FirstName:</label>
 24:                 <%= Html.TextBox("FirstName") %>
 25:                 <%= Html.ValidationMessage("FirstName", "*") %>
 26:             </p>
 27:             <p>
 28:                 <label for="LastName">LastName:</label>
 29:                 <%= Html.TextBox("LastName") %>
 30:                 <%= Html.ValidationMessage("LastName", "*") %>
 31:             </p>
 32:             <p>
 33:                 <input type="submit" value="Create" />
 34:             </p>
 35:         </fieldset>
 36:     <% } %>
 37:     <div>
 38:         <%=Html.ActionLink("Back to List", "Index") %>
 39:     </div>
 40: </asp:Content>

To try this view, run the application, go to http://localhost:3382/members/index and click the Create New link. Or, immediately type in the url http://localhost:3382/members/Create:

ASPNETMVC_QS3_07

Note: The id property of a member is auto-generated by the data access layer, so you can safely delete this in the view because a user should not be able to fill this in:

ASPNETMVC_QS3_08

This view uses the Html.TextBox helper to generate textboxes to fill in the required data.

Also notice the Html.BeginForm statement:

  1: <% using (Html.BeginForm()) {%>
which will generate a form-element:
  1: <form action=/members/Createmethod=”post”></form>

So, when the Create button is clicked (which is of input type submit), a new POST request to http://localhost/members/create is triggered and all form data will be passed with it. This means that the action method Create of the MembersController will be executed. But hold on… again? When we clicked the Create New link previously, this same action method was executed? What is happening?

To understand how it works, you have to know the difference between GET and POST requests. When we clicked the Create New link, a new GET request was triggered, causing the Create action method to execute. We could have explicitly written the Create action method as:

  1: [AcceptVerbs(HttpVerbs.Get)]
  2: public ActionResult Create()
  3: {
  4:     return View();
  5: }

If you don’t specify the AcceptVerbs attribute, it defaults to HttpVerbs.Get. That’s why the Create New link executes the Create action method when clicked.

But now, when clicking the Create button, we have the intention of creating a new member – which is potentially an unsafe operation, and therefore should be handled by a POST request instead of a GET request. Indeed, the generated Create button triggers a POST request, and in order to handle it, we have to create a new Create action method in the MembersController but this time decorated with HttpVerbs.Get, and accepting a member parameter.

  1: [AcceptVerbs(HttpVerbs.Post)]
  2: public ActionResult Create(Member member)
  3: {
  4:     // Use model to create this new member
  5:     MemberService.CreateMember(member);
  6:     // Redirect to Details action method and pass the new id
  7:     return RedirectToAction("Details", new { id = member.ID });
  8: }

Again, thanks to model binding the member parameter is created and its properties (FirstName and LastName) are initialized with the data from the form – so we don’t have to do anything special to get the data out of the request.  Then, the model is used to actually create the new member and then a RedirectToAction result is returned to trigger a redirection passing the name of the action method to redirect to (Details) and the data to be passed to this action method (the id).

Previously we already wrote this Details action method, so it will already work: when the new member is created, its details will be shown.

Test it: run the application, and create a new member:

    ASPNETMVC_QS3_09  

When you click Create, the member will be created and you will be redirected to the details view:

ASPNETMVC_QS3_10

As you see, the id was generated fine. Now click the Back to List link, and the new member will be visible in the list:

ASPNETMVC_QS3_11

Task 3: making the Edit link work

Update our Model code so that we can update an existing member. Open the MemberService class in the Model folder, and add the following method:

  1: public static void UpdateMember(Member member)
  2: {
  3:     // Find member in collection
  4:     Member foundMember = members.Find(m => m.ID == member.ID);
  5:     // Update member
  6:     foundMember.FirstName = member.FirstName;
  7:     foundMember.LastName = member.LastName;
  8: }

The Edit link in the Index.aspx view looked like:

  1: <%= Html.ActionLink("Edit", "Edit", new { id=item.ID }) %>

This means that we have to add a new action method called Edit to the MembersController that will handle the GET request (and show the form to edit a member):

  1: [AcceptVerbs(HttpVerbs.Get)]
  2: public ActionResult Edit(int id)
  3: {
  4:     // Get member details using model
  5:     Member member = MemberService.GetMember(id);
  6:     // Return default view and pass member
  7:     return View(member);
  8: }

If the Edit link is clicked, the Edit action method of the MembersController will be executed, and in this method we first get the member details for the passed member id, and then return the default view for editing a member. This view does not exist yet, so right click the Edit action method and select Add View, and make sure everything is filled in as follows:

ASPNETMVC_QS3_12

Make sure that:

  • The View name is called Edit.
  • You check the Create a strongly typed view check box, and set the View data class to MvcApplication1.Models.Member. This way, we will be able to access the member data in the view in a strongly typed way.
  • Select Edit as the View content. This will generate code that displays the editing of a member.

Click Add, and the Edit.aspx view will be created in the folder Views/Members. In this view, remove the id like you did in the Create view, because we don’t want users modifying it. Run the application and click the Edit link next to a member:

ASPNETMVC_QS3_13

So change first name and/or last name and click Save. Guess what? An error is shown, because – you guessed it – we didn’t write code to handle the POST request yet.

Add new action method called Edit again but this time to handle POST request (and actually saves the updated member using the model). Open the MembersController class and add the following action method:

  1: [AcceptVerbs(HttpVerbs.Post)]
  2: public ActionResult Edit(Member member)
  3: {
  4:     // Use model to update this existing member
  5:     MemberService.UpdateMember(member);
  6:     // Redirect to Details action method and pass the id
  7:     return RedirectToAction("Details", new { id = member.ID });
  8: }

Run the application again, and rename Loren Lyle to Laura Lyle:

ASPNETMVC_QS3_14

Click Save:

ASPNETMVC_QS3_15

And if you go back to the list, it will also display the new name:

ASPNETMVC_QS3_16

Task 4: making the Delete link work

As always, first update our Model code so that we can delete an existing member. Open the MemberService class in the Model folder, and add the following method:

  1: public static void DeleteMember(int id)
  2: {
  3:     // Find member in collection
  4:     Member memberToDelete = GetMember(id);
  5:     // Delete member
  6:     members.Remove(memberToDelete);
  7: }

There wasn’t a Delete  link in the Index.aspx view yet, so we will add it now:

ASPNETMVC_QS3_17

This means that we have to add a new action method called Delete to the MembersController that will handle the GET request (and show the form to delete the member):

  1: [AcceptVerbs(HttpVerbs.Get)]
  2: public ActionResult Delete(int id)
  3: {
  4:     // Get member details using model
  5:     Member member = MemberService.GetMember(id);
  6:     // Return default view and pass member
  7:     return View(member);
  8: }

If the Delete link is clicked, the Delete action method of the MembersController will be executed, and in this method we first get the member details for the passed member id, and then return the default view for deleting a member. This view does not exist yet, so right click the Delete action method and select Add View, and make sure everything is filled in as follows:

ASPNETMVC_QS3_18

Make sure that:

  • The View name is called Delete.
  • You check the Create a strongly typed view check box, and set the View data class to MvcApplication1.Models.Member. This way, we will be able to access the member data in the view in a strongly typed way.
  • Select Empty as the View content. We will add some HTML manually.

Click Add, and the Delete.aspx view will be created in the folder Views/Members. Make this view look like:

  1: <%@ Page Title="" Language="C#"
  2:          MasterPageFile="~/Views/Shared/Site.Master"
  3:          Inherits="System.Web.Mvc.ViewPage<
  4:                       MvcApplication1.Models.Member>" %>
  5: <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"
  6:              runat="server">
  7:  Delete
  8: </asp:Content>
  9: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
 10:              runat="server">
 11:     <h2>Delete</h2>
 12:    
 13:     Do you really want to delete <% = Model.FirstName %> <% =
 14:     Model.LastName %>?
 15:    
 16:     <% using (Html.BeginForm(new { id = Model.ID }))
 17:        { %>
 18:        <p>
 19:             <input type="submit" value="Delete" />
 20:         </p>
 21:     <% } %>
 22:     <div>
 23:         <%=Html.ActionLink("Back to List", "Index") %>
 24:     </div>
 25: </asp:Content>

To handle the actual Delete, add new action method called Delete again but this time to handle POST request (and actually deletes the requested member using the model). Open the MembersController class and add the following action method:

  1: [AcceptVerbs(HttpVerbs.Post)]
  2: public ActionResult Delete(Member member)
  3: {
  4:     // Use model to delete this existing member
  5:     MemberService.DeleteMember(member.ID);
  6:     // Redirect to Index action method
  7:     return RedirectToAction("Index");
  8: }

That should do it! Run the application, and delete the member Todd Lorn:

ASPNETMVC_QS3_19

Click Delete, and the member will be deleted:

ASPNETMVC_QS3_20

May 6, 2010 23:41 by lustuyck
E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

ASP.NET MVC QuickStart 2: Implement model, controller and view

Objectives

In this Hands-On Lab, you will create functionality to display a list of members. In particular, you will:

  • Create a model
  • Create a controller
  • Create a view

System requirements

You must have the following items to complete this lab:

  • Microsoft Visual Studio 2008 SP1 (professional edition)
  • Microsoft ASP.NET MVC 1.0

Prequisites

You must have the following skills to understand this lab:

  • Fundamental knowledge of software development in .NET 3.5
  • Some experience in ASP.NET web development

This lab builds further on the QuickStart 1 code.

Task 1: create a model

In ASP.NET MVC, the model is responsible for providing the needed data and applying the business logic. Therefore, we will start by creating the model for our web application. We will first create a Member business entity, so right click the Model folder, select Add -> Class and call the new class Member.cs:

ASPNETMVC_QS2_01

Keep it simple, and define the following properties:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Web;
  5: namespace MvcApplication1.Models
  6: {
  7:     public class Member
  8:     {
  9:         public int ID { get; set; }
 10:         public string FirstName { get; set; }
 11:         public string LastName { get; set; }       
 12:     }
 13: }
The model is also responsible for data access operations, so add another class to the Model folder and call it MemberService.cs:
  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Web;
  5: namespace MvcApplication1.Models
  6: {
  7:     /// <summary>
  8:     /// For simplicity, MemberService mimics a member service providing
  9:     /// basic member operations and working with mock data.
 10:     /// </summary>
 11:     public class MemberService
 12:     {
 13:         private static List<Member> members;
 14:         static MemberService()
 15:         {
 16:             // Create some dummy members
 17:             members = new List<Member>();
 18:             members.Add(new Member()
 19:               { ID = 0, FirstName = "Geoffrey", LastName = "Denver" });
 20:             members.Add(new Member()
 21:               { ID = 1, FirstName = "Todd", LastName = "Lorn" });
 22:             members.Add(new Member()
 23:               { ID = 2, FirstName = "Loren", LastName = "Lyle" });
 24:             members.Add(new Member()
 25:               { ID = 3, FirstName = "Ralphie", LastName = "Ethan" });
 26:             members.Add(new Member()
 27:               { ID = 4, FirstName = "Mervyn", LastName = "Tyler" });
 28:         }
 29:         public static List<Member> GetMembers()
 30:         {
 31:             return members;
 32:         }
 33:     }
 34: }

At this point, we have created a very basic model that we can use to retrieve members.

Task 2: create a controller

The next step is to create a controller that will be responsible for retrieving the member data and passing this data to a view. To do that, right click the Controllers folder, select Add -> Controller and call it MembersController:

ASPNETMVC_QS2_02

Click Add. The new file membersController.cs will now be added to the Controllers folder. Modify it as follows:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Web;
  5: using System.Web.Mvc;
  6: using System.Web.Mvc.Ajax;
  7: using MvcApplication1.Models;
  8: namespace MvcApplication1.Controllers
  9: {
 10:     public class MembersController : Controller
 11:     {
 12:         //
 13:         // GET: /Members/
 14:         public ActionResult Index()
 15:         {
 16:             // Get a list of members using the model
 17:             List<Member> members = MemberService.GetMembers();
 18:            
 19:             // return this list to the default view
 20:             return View(members);
 21:         }
 22:     }
 23: }

Put a breakpoint on the first line of the Index method and hit F5 to debug the web application. The first time you will see the following dialog:

ASPNETMVC_QS2_03

Just click OK because we want to enable debugging, and the web page will appear. Then, modify the URL to trigger the Index action of the MembersController we just created, as follows:

ASPNETMVC_QS2_04

When you do this, the routing system will map this URL to the Index action method of the Members controller, and so the Index method will execute:

ASPNETMVC_QS2_05

Hit F5 again, and then you’ll see the following error appear:

ASPNETMVC_QS2_06

This is normal, because the Index action method tries to find the default view Index.aspx in the Views/Members folder, but we didn’t create that view yet.

Task 3: create a view

In this task, we will create a view to display a list of members. To do that, open MembersController.cs and right click the Index method:

ASPNETMVC_QS2_07

Then select Add View and fill in the required fields as follows:

ASPNETMVC_QS2_08

Make sure that:

  • The View name is called Index.
  • You check the Create a strongly typed view check box, and set the View data class to MvcApplication1.Models.Member. This way, we will be able to access the member data in the view in a strongly typed way.
  • Select List as the View content. This will generate code that displays a list of members.

Click Add. The view Index.aspx will be generated and added to the Views/Members folder of the project:

  1: <%@ Page Title="" Language="C#"
  2:          MasterPageFile="~/Views/Shared/Site.Master"
  3:          Inherits="System.Web.Mvc.ViewPage<IEnumerable<
  4:                            MvcApplication1.Models.Member>>" %>
  5: <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"  
  6:              runat="server">
  7:  Index
  8: </asp:Content>
  9: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
 10:              runat="server">
 11:     <h2>Index</h2>
 12:     <table>
 13:         <tr>
 14:             <th></th>
 15:             <th>
 16:                 ID
 17:             </th>
 18:             <th>
 19:                 FirstName
 20:             </th>
 21:             <th>
 22:                 LastName
 23:             </th>
 24:         </tr>
 25:     <% foreach (var item in Model) { %>
 26:    
 27:         <tr>
 28:             <td>
 29:                 <%= Html.ActionLink("Edit", "Edit", new {
 30:                                    /* id=item.PrimaryKey */ }) %> |
 31:                 <%= Html.ActionLink("Details", "Details", new {
 32:                                    /* id=item.PrimaryKey */ })%>
 33:             </td>
 34:             <td>
 35:                 <%= Html.Encode(item.ID) %>
 36:             </td>
 37:             <td>
 38:                 <%= Html.Encode(item.FirstName) %>
 39:             </td>
 40:             <td>
 41:                 <%= Html.Encode(item.LastName) %>
 42:             </td>
 43:         </tr>
 44:    
 45:     <% } %>
 46:     </table>
 47:     <p>
 48:         <%= Html.ActionLink("Create New", "Create") %>
 49:     </p>
 50: </asp:Content>

The view already contains HTML to display the list of members, and the code is very straightforward. Notice:

  • the foreach statement that is used to loop all elements of the Model property. Because we made it a strongly typed view, it inherits from ViewPage<IEnumerable<MvcApplication1.Models.Member>>, and therefore the Model property if of type IEnumerable<MvcApplication1.Models.Member> and thus we can use it in a strongly typed way.
  • The use of Html.ActionLink helper method to generate edit, create and details links. So you don’t have to write links yourself, instead always let ASP.NET MVC generate these for you (it will use routing mechanism to do so).
  • The use of Html.Encode helper method, which encodes HTML to avoid cross-site scripting.

One more thing to do manually: replace the documented code in the action links so that we assign the primary key to each member instance for the Edit and Details links:

  1: <%= Html.ActionLink("Edit", "Edit", new { id=item.ID }) %> |
  2: <%= Html.ActionLink("Details", "Details", new { id=item.ID })%>

Run the web application again, change the url to http://localhost:3382/members/index and the list of members will be shown:

ASPNETMVC_QS2_09

Note: none of the generated links work at this point, so that’s what we’ll do next.

May 6, 2010 23:36 by lustuyck
E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

ASP.NET MVC QuickStart 1: Introducing ASP.NET MVC

Objectives

In this Hands-On Lab, you will be introduced to the ASP.NET MVC framework. In particular, you will:

  • Understand key benefits of ASP.NET MVC
  • Understand what the MVC design pattern is about
  • Create an ASP.NET MVC application
  • Understand ASP.NET MVC default routing

System requirements

You must have the following items to complete this lab:

  • Microsoft Visual Studio 2008 SP1 (professional edition)
  • Microsoft ASP.NET MVC 1.0

Prequisites

You must have the following skills to understand this lab:

  • Fundamental knowledge of software development in .NET 3.5
  • Some experience in ASP.NET web development

Task 1: Understand key benefits of ASP.NET MVC

Before you begin, you should understand the main advantages of ASP.NET MVC and why it is important to adopt it in most of your projects:

  • MVC design pattern: the ASP.NET MVC framework is a modern MVC implementation
  • Extensibility: the ASP.NET MVC framework consists of a number of independent components that can be completely replaced with your own implementation if needed. Your options are:
    • Use the default implementation
    • Derive a subclass of the default implementation to tweak behavior
    • Replace a component entirely with a new implementation
  • Testability: the ASP.NET MVC framework is made to be tested using today’s testing and mocking frameworks.
  • Full control: no generated HTML that violates standards, because you are in control over the rendered HTML, scripts and markup. This also means that there is no hidden magic going on. As an example, there is no ViewState anymore, so pages are smaller and faster to load.
  • Routing system: ASP.NET MVC works with a powerful routing system that maps search-engine friendly URL’s to actions.
  • Stateless nature: embraces stateless nature of the web instead of trying to hide it and therefore avoiding complex situations.

Task 2: Understand what the MVC pattern is about

ASP.NET MVC is based on the MVC architectural pattern, which stands for Model-View-Controller, and is all about keeping things organized via separation of concerns:

ASPNETMVCSQ1_01

This means that we have 3 areas of responsibility:

  • Model: contains the business and data logic.
  • View: is responsible for presentation logic, so this is your user interface
  • Controller: contains application logic; here we receive user input and react on it by retrieving data from the model and asking views to render themselves using this data. So the controllers act as a bridge between your model and the user interface.

As an example, if an event occurs (user clicks a button on a web page), then the controller takes action and reacts on this event by using the model to execute business and data logic (retrieving data) and asking a specific view to render itself using this data:

ASPNETMVCSQ1_02

 

The goal of this separation is that each area has its own concern and concerns should never be mixed; and as a result it is possible to modify either the visual appearance of the application, the application logic or the underlying business rules without affecting the other.

Task 3: Create an ASP.NET MVC application

In this task you will create and configure an empty ASP.NET MVC application project using the MVC Visual Studio template.

Start Visual Studio 2008. Click File -> New -> Project, click the Web project type and select ASP.NET MVC Web Application. Give your project a name ‘MvcApplication1’ and location and click OK:

ASPNETMVCSQ1_03

In a next dialog, you will get the option of creating a unit test project too. For now, check the ‘No, do not create a unit test project’ option and click OK:

ASPNETMVCSQ1_04

As a result, the solution and web project will be created, containing some default folders and files, structured to support the MVC pattern:

ASPNETMVCSQ1_05

 

 

As you see, the most important folders are:

  • Controllers: contains all controller classes.
  • Models: contains all models and underlying business and data logic.
  • Views: contains all views, for example .aspx or .ascx files.
  • Shared: contains all shared views, for example master pages…
  • Scripts: contains all java script files.
  • Content: contains content files, for example images, style sheets…

If you run this, you will see this simple web application:

ASPNETMVCSQ1_06

Task 4: Understand ASP.NET MVC default routing

When the user types in a URL, a routing system takes care of mapping this incoming request to a specific action method of a specific controller, using a default naming convention.

This means that a URL in the form of http://localhost, http://localhost/home or http://localhost/home/index all map to an action method called ‘Index’ of a controller called HomeController. We will later see how this routing from URL to controller works and can be modified, but for now just assume that routing takes care using some default naming convention.

The controller HomeController is a normal C# class (inheriting from Controller) that is created in the Controllers folder of the project, and the action Index is a normal C# method in that HomeController class:

  1: public class HomeController : Controller
  2: {
  3:     public ActionResult Index()
  4:     {
  5:         ViewData["Message"] = "Welcome to ASP.NET MVC!";
  6:         return View();
  7:     }
  8: }

When the Index action method gets executed, it returns a view which has to be rendered. Again, using the default naming convention it knows that it has to render the Index.aspx view in the Views/Home folder of the project:

  1: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
  2:          Inherits="System.Web.Mvc.ViewPage" %>
  3: <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent"
  4:              runat="server">
  5:     Home Page
  6: </asp:Content>
  7: <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent"
  8:              runat="server">
  9:     <h2><%= Html.Encode(ViewData["Message"]) %></h2>
 10:     <p>
 11:         To learn more about ASP.NET MVC visit <a
 12:                 href="http://asp.net/mvc" title="ASP.NET MVC
>http://asp.net/mvc</a>.
 13:                 Website"
 14:     </p>
 15: </asp:Content>

In this case, the controller Index action stores a string in ViewData (which is a built-in loosely typed dictionary) , and because the Index.aspx view has also access to it, this data can be used in the view. So, ViewData is a way to pass data from the controller to the view.

Note: obviously, passing data in a loosely typed way is evil. In the next lab, we will use a strongly typed way to do this!

May 6, 2010 07:18 by lustuyck
E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed