<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Ludwig's Blog</title>
	<atom:link href="http://ludwigstuyck.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://ludwigstuyck.wordpress.com</link>
	<description>Adventures in .NET</description>
	<lastBuildDate>Thu, 05 Nov 2009 20:44:48 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='ludwigstuyck.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/3d9e6a8196018b8464dc7cfb8df70025?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Ludwig's Blog</title>
		<link>http://ludwigstuyck.wordpress.com</link>
	</image>
			<item>
		<title>ASP.NET MVC QuickStart 8: partial updates using jquery</title>
		<link>http://ludwigstuyck.wordpress.com/2009/11/05/asp-net-mvc-quickstart-8-partial-updates-using-jquery/</link>
		<comments>http://ludwigstuyck.wordpress.com/2009/11/05/asp-net-mvc-quickstart-8-partial-updates-using-jquery/#comments</comments>
		<pubDate>Thu, 05 Nov 2009 20:39:51 +0000</pubDate>
		<dc:creator>Ludwig Stuyck</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://ludwigstuyck.wordpress.com/?p=356</guid>
		<description><![CDATA[&#8230;continued from part 7.
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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=356&subd=ludwigstuyck&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>&#8230;continued from <a href="http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-7-action-filters/" target="_self">part 7</a>.</p>
<h2>Objectives</h2>
<p>In this Hands-On Lab, you will learn how to do partial updates in JSON format using jquery. In particular, you will:<br />
- Task 1: add new controller action and view<br />
- Task 2: add controller action method to get list of members<br />
- Task 3: add jquery to populate members combo box<br />
- Task 4: show member details</p>
<h2>System requirements</h2>
<p>You must have the following items to complete this lab:<br />
- Microsoft Visual Studio 2008 SP1 (professional edition)<br />
- Microsoft ASP.NET MVC 1.0</p>
<h2>Prequisites</h2>
<p>You must have the following skills to understand this lab:<br />
- Fundamental knowledge of software development in .NET 3.5<br />
- Some experience in ASP.NET web development<br />
This lab builds further on the QuickStart 7 code.</p>
<h2>Task 1: add new controller action and view</h2>
<p>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:</p>
<pre><span style="color:#993366;">public ActionResult Index2()
{
    // return this list to the default view
    return View();
}</span></pre>
<p>Also add a view for this action method:</p>
<div id="attachment_361" class="wp-caption alignnone" style="width: 288px"><img class="size-medium wp-image-361" title="9-1" src="http://ludwigstuyck.files.wordpress.com/2009/11/9-11.jpg?w=278&#038;h=300" alt="Add View" width="278" height="300" /><p class="wp-caption-text">Add View</p></div>
<p>In this case we are not going to create a strongly typed view because the needed data will be retrieved asynchronously using jquery.</p>
<p>Modify the generated view. First, place a combo box in the view:</p>
<pre><span style="color:#888888;">&lt;%@ Page Title="" Language="C#"
         MasterPageFile="~/Views/Shared/Site.Master"                                                  
         Inherits="System.Web.Mvc.ViewPage" %&gt;</span>
<span style="color:#888888;">&lt;asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"
             runat="server"&gt;
  Index2
&lt;/asp:Content&gt;</span>
<span style="color:#888888;">&lt;asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
             runat="server"&gt;</span>
<span style="color:#888888;">    &lt;h2&gt;Index2&lt;/h2&gt;

    <span style="color:#993366;">&lt;% &lt;select id="MembersDropDownList" /&gt;</span></span>
<span style="color:#888888;">&lt;/asp:Content&gt;</span></pre>
<p> To fill this combo box with members using AJAX, we have to:</p>
<ul>
<li>Add a controller action method that returns a list of members</li>
<li>Write some jquery that uses the controller action method to populate the combo box when the page has been rendered</li>
</ul>
<p>We will do this in the next tasks.</p>
<h2>Task 2: add controller action method to get list of members</h2>
<p>Add a new action method called GetCustomers to the MembersController:</p>
<pre><span style="color:#993366;"> public JsonResult GetMembers()
{
    // Get a list of members using the model
    List&lt;Member&gt; members = MemberService.GetMembers();

    // Return list of members as JSON
    return this.Json(members);
}</span></pre>
<p>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 <a href="http://json.org">http://json.org</a>).</p>
<h2>Task 3: add jquery to populate members combo box</h2>
<p>Now we have to consume the JSON data and populate the combo box with members.</p>
<p>First we need references to the jquery javascript libraries, so open up the Site.Master and add the needed references:</p>
<pre><span style="color:#808080;">&lt;head runat="server"&gt;
  &lt;title&gt;
    &lt;asp:ContentPlaceHolder ID="TitleContent" runat="server" /&gt;
  &lt;/title&gt;
  &lt;link href="../../Content/Site.css" rel="stylesheet"
        type="text/css" /&gt;
  <span style="color:#993366;">&lt;script src="/Scripts/jQuery-1.3.2.js"
          type="text/javascript"&gt;&lt;/script&gt;
  &lt;script src="/Scripts/jquery-1.3.2.min.js"
          type="text/javascript"&gt;&lt;/script&gt;
</span>&lt;/head&gt;</span></pre>
<p>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:</p>
<pre><span style="color:#808080;">&lt;asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
             runat="server"&gt;</span>
<span style="color:#808080;">   <span style="color:#993366;"> &lt;script type="text/javascript"&gt;
        $(document).ready(function()
        {       
            // if the DOM is loaded, start retrieving the members
            $.getJSON(
                "/Members/GetMembers", null, function(data)
                {
                    addMembers(data);
                })       
        });</span></span>
<span style="color:#993366;">        function addMembers(data)
        {
            // Get the DOM reference to the drop-down list.        
            var membersDropDownList = $("#MembersDropDownList");

            // Loop through each member and populate the combo box.           
            $.each(data, function(index, optionData) {
                membersDropDownList.append("&lt;option value='"
                    + optionData.ID
                    + "'&gt;" + optionData. LastName                                               
                    + "&lt;/option&gt;");
            });       
        };
    &lt;/script&gt;</span>
<span style="color:#808080;">    &lt;h2&gt;Index2&lt;/h2&gt;

    &lt;select id="MembersDropDownList" /&gt;

&lt;/asp:Content&gt;</span></pre>
<p>Take your time to study and understand the jquery syntax.</p>
<p>Now start the application and go to the page <em>“/members/index2”</em>. If everything works, the combo box should be populated:</p>
<div id="attachment_365" class="wp-caption alignnone" style="width: 310px"><img class="size-medium wp-image-365" title="9-2" src="http://ludwigstuyck.files.wordpress.com/2009/11/9-2.jpg?w=300&#038;h=263" alt="Index2" width="300" height="263" /><p class="wp-caption-text">Index2</p></div>
<h2>Task 4: show member details</h2>
<p>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:</p>
<pre><span style="color:#993366;">public JsonResult GetMemberDetails(int memberID)
{  
    // Get member details using model
    Member m = MemberService.GetMember(memberID);</span>
<span style="color:#993366;">    // Return list of members as JSON
    return this.Json(m);
}</span></pre>
<p>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 <em>jquery</em>:</p>
<pre><span style="color:#808080;">&lt;asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
             runat="server"&gt;</span>
<span style="color:#808080;">    &lt;script type="text/javascript"&gt;
        $(document).ready(function()
        {       
            $.getJSON(
                "/Members/GetMembers", null, function(data)
                {
                    addMembers(data);
                })

            <span style="color:#993366;">var membersDropDownList = $("#MembersDropDownList");
            membersDropDownList.change(function() {                                
                populateDetails(this.value);
            })
</span>        });</span>
<span style="color:#808080;">        <span style="color:#993366;">function populateDetails(id)
        {
            $.getJSON("/Members/GetMemberDetails",
                {memberID : id }, function(data) {                
                    $("#FirstName").html(data.FirstName);
                    $("#LastName").html(data.LastName);
                });
        }</span></span>
<span style="color:#808080;">        function addMembers(data)
        {
            // Get the DOM reference to the drop-down list.        
            var membersDropDownList = $("#MembersDropDownList");

            // Loop through each member and populate the combo box.           
            $.each(data, function(index, optionData) {
                membersDropDownList.append("&lt;option value='"
                    + optionData.ID
                    + "'&gt;" + optionData.LastName
                    + "&lt;/option&gt;");
            });       
        };
    &lt;/script&gt;</span>
<span style="color:#808080;">    &lt;h2&gt;Index2&lt;/h2&gt;   

    &lt;select id="MembersDropDownList"&gt;&lt;/select&gt;

    <span style="color:#993366;">&lt;p /&gt;

    &lt;div&gt;First name: &lt;span id="FirstName"&gt;&lt;/span&gt;&lt;/div&gt;
    &lt;div&gt;Last name: &lt;span id="LastName"&gt;&lt;/span&gt;&lt;/div&gt;   </span>           
&lt;/asp:Content&gt;</span></pre>
<p>Start the application again, go to the page <em>“/members/index2”</em> and select another member. The details should become visible:</p>
<div id="attachment_366" class="wp-caption alignnone" style="width: 310px"><img class="size-medium wp-image-366" title="9-3" src="http://ludwigstuyck.files.wordpress.com/2009/11/9-3.jpg?w=300&#038;h=263" alt="Index2" width="300" height="263" /><p class="wp-caption-text">Index2</p></div>
<p>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:</p>
<pre><span style="color:#808080;">&lt;script type="text/javascript"&gt;
        $(document).ready(function()
        {       
            $.getJSON(
                "/Members/GetMembers", null, function(data)
                {
                    addMembers(data);
                    <span style="color:#993366;">populateDetails(membersDropDownList.val());
</span>                })

            var membersDropDownList = $("#MembersDropDownList");
            membersDropDownList.change(function() {                                
                populateDetails(this.value);
            })                                                                  
        });
&lt;/script&gt;</span>
If you try it now, the member details will be visible when the page is first loaded.</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ludwigstuyck.wordpress.com/356/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ludwigstuyck.wordpress.com/356/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ludwigstuyck.wordpress.com/356/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ludwigstuyck.wordpress.com/356/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ludwigstuyck.wordpress.com/356/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ludwigstuyck.wordpress.com/356/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ludwigstuyck.wordpress.com/356/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ludwigstuyck.wordpress.com/356/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ludwigstuyck.wordpress.com/356/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ludwigstuyck.wordpress.com/356/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=356&subd=ludwigstuyck&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ludwigstuyck.wordpress.com/2009/11/05/asp-net-mvc-quickstart-8-partial-updates-using-jquery/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2417489f4fa437ef00401ab389ffbe9a?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">Ludwig Stuyck</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/11/9-11.jpg?w=278" medium="image">
			<media:title type="html">9-1</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/11/9-2.jpg?w=300" medium="image">
			<media:title type="html">9-2</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/11/9-3.jpg?w=300" medium="image">
			<media:title type="html">9-3</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC QuickStart 7: action filters</title>
		<link>http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-7-action-filters/</link>
		<comments>http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-7-action-filters/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 11:10:22 +0000</pubDate>
		<dc:creator>Ludwig Stuyck</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://ludwigstuyck.wordpress.com/?p=339</guid>
		<description><![CDATA[&#8230;continued from part 6.
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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=339&subd=ludwigstuyck&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>&#8230;continued from <a href="http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-6-automated-testing/" target="_self">part 6</a>.</p>
<h2>Objectives</h2>
<p>In this Hands-On Lab, you will be introduced to the ASP.NET MVC framework. In particular, you will:</p>
<ul>
<li>Task 1: understand action filters</li>
<li>Task 2: built-in action filters</li>
<li>Task 3: write a custom action filter</li>
</ul>
<h2>System requirements</h2>
<p>You must have the following items to complete this lab:</p>
<ul>
<li>Microsoft Visual Studio 2008 SP1 (professional edition)</li>
<li>Microsoft ASP.NET MVC 1.0</li>
</ul>
<h2>Prequisites</h2>
<p>You must have the following skills to understand this lab:</p>
<ul>
<li>Fundamental knowledge of software development in .NET 3.5</li>
<li>Some experience in ASP.NET web development</li>
</ul>
<p>This lab builds further on the QuickStart 6 code.</p>
<h2>Task 1: understand action filters</h2>
<p>An action filter is behavior that can be attached to controllers and action methods. They inject extra logic in the request processing pipeline:</p>
<ul>
<li>before and after an action method runs</li>
<li>before and after action results are executed</li>
<li>during exception handling</li>
</ul>
<p>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.</p>
<p>The MVC framework knows about following filter types:</p>
<pre><strong>Filter type            Interface              When run                         Default implementation</strong>
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 </pre>
<h2>Task 2: built-in action filters</h2>
<p>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:</p>
<pre><span style="color:#800080;">[Authorize()]
[OutputCache(Duration=60)]
<span style="color:#888888;">public ActionResult Index()
{
   …
}</span></span></pre>
<p>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.</p>
<h2>Task 3: write a custom action filter</h2>
<p>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.</p>
<p>To start, add a new folder to the MvcApplication1 web application and call it ActionFilters. Right click this folder and select Add -&gt; Class, and name it LogAttribute, and implement it with the following code:</p>
<pre><span style="color:#800080;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Diagnostics;</span>
<span style="color:#800080;">namespace MvcApplication1.ActionFilters
{
    public class LogAttribute : ActionFilterAttribute,
                    IActionFilter, IResultFilter, IExceptionFilter
    {</span>
<span style="color:#800080;">        #region IActionFilter Members</span>
<span style="color:#800080;">        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {
            Log("OnActionExecuted", filterContext.RouteData);
        }</span>
<span style="color:#800080;">        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            Log("OnActionExecuting", filterContext.RouteData);
        }</span>
<span style="color:#800080;">        #endregion</span>
<span style="color:#800080;">        #region IResultFilter Members</span>
<span style="color:#800080;">        void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)
        {
            Log("OnResultExecuted", filterContext.RouteData);
        }</span>
<span style="color:#800080;">        void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext)
        {
            Log("OnResultExecuting", filterContext.RouteData);
        }</span>
<span style="color:#800080;">        #endregion</span>
<span style="color:#800080;">        #region IExceptionFilter Members</span>
<span style="color:#800080;">        public void OnException(ExceptionContext filterContext)
        {
            Log("OnException", filterContext.RouteData);
        }</span>
<span style="color:#800080;">        #endregion</span>
<span style="color:#800080;">        #region Log</span>
<span style="color:#800080;">        public static void Log(string message, RouteData routeData)
        {
            Trace.WriteLine(
</span><span style="color:#800080;">                string.Format("{0}, controller = {1}, action = {2}",
                message,
                routeData.Values["controller"],
                routeData.Values["action"]));
        }</span>
<span style="color:#800080;">        #endregion
    }
}</span></pre>
<p>This code is very straightforward, notice the following:</p>
<ul>
<li>the LogAttribute class inherits from ActionFilterAttribute, which provides you with the default implementation.</li>
<li>the LogAttribute class implements three interfaces: IActionFilter, IResultFilter and IExceptionFilter.</li>
<li>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…).</li>
</ul>
<p>Then add the following using statement on top of the MembersController:</p>
<pre><span style="color:#800080;">using MvcApplication1.ActionFilters;</span></pre>
<p>Now you can apply the Log action filter, for example, decorate the action method Index of the MembersController with it:</p>
<pre><span style="color:#800080;">[Log]
public ActionResult Index()
{
    // Get a list of members using the model
    List&lt;Member&gt; members = MemberService.GetMembers();

    // return this list to the default view
    return View(members);
}</span></pre>
<p>Hit F5 to start the web application, go to <a href="http://localhost:3382/members">http://localhost:3382/members</a> and have a look at the output window in visual studio:</p>
<div id="attachment_341" class="wp-caption alignnone" style="width: 693px"><img class="size-full wp-image-341" title="Output window" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs70.jpg?w=683&#038;h=475" alt="Output window" width="683" height="475" /><p class="wp-caption-text">Output window</p></div>
<p>As you see, the various steps in the pipeline have been written to the output window.</p>
<p>Note: if you would throw an exception in the Index action method, the OnException step would be executed too.</p>
<p>Go to <a href="http://ludwigstuyck.wordpress.com/2009/11/05/asp-net-mvc-quickstart-8-partial-updates-using-jquery/" target="_self">next part</a>.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ludwigstuyck.wordpress.com/339/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ludwigstuyck.wordpress.com/339/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ludwigstuyck.wordpress.com/339/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ludwigstuyck.wordpress.com/339/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ludwigstuyck.wordpress.com/339/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ludwigstuyck.wordpress.com/339/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ludwigstuyck.wordpress.com/339/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ludwigstuyck.wordpress.com/339/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ludwigstuyck.wordpress.com/339/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ludwigstuyck.wordpress.com/339/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=339&subd=ludwigstuyck&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-7-action-filters/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2417489f4fa437ef00401ab389ffbe9a?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">Ludwig Stuyck</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs70.jpg" medium="image">
			<media:title type="html">Output window</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC QuickStart 6: automated testing</title>
		<link>http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-6-automated-testing/</link>
		<comments>http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-6-automated-testing/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 08:43:57 +0000</pubDate>
		<dc:creator>Ludwig Stuyck</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://ludwigstuyck.wordpress.com/?p=328</guid>
		<description><![CDATA[&#8230;continued from part 5.
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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=328&subd=ludwigstuyck&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>&#8230;continued from <a href="http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-5-routing/" target="_self">part 5</a>.</p>
<h2>Objectives</h2>
<p>In this Hands-On Lab, you will be introduced to the ASP.NET MVC framework. In particular, you will:</p>
<ul>
<li>Task 1: add a unit test project</li>
<li>Task 2: Test model</li>
<li>Task 3: Test controller</li>
<li>Task 4: Test routing</li>
</ul>
<h2>System requirements</h2>
<p>You must have the following items to complete this lab:</p>
<ul>
<li>Microsoft Visual Studio 2008 SP1 (professional edition)</li>
<li>Microsoft ASP.NET MVC 1.0</li>
</ul>
<h2>Prequisites</h2>
<p>You must have the following skills to understand this lab:</p>
<ul>
<li>Fundamental knowledge of software development in .NET 3.5</li>
<li>Some experience in ASP.NET web development</li>
</ul>
<p>This lab builds further on the QuickStart 5 code.</p>
<h2>Task 1: add a unit test project</h2>
<p>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.</p>
<p>Let’s start off with adding a unit test project: right click the MvcApplication1 solution and select Add -&gt; New project. Select Test Project in Test project types and fill in name and location:</p>
<div id="attachment_329" class="wp-caption alignnone" style="width: 877px"><img class="size-full wp-image-329" title="Add new project" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs60.jpg?w=867&#038;h=561" alt="Add new project" width="867" height="561" /><p class="wp-caption-text">Add new project</p></div>
<p>Click OK. A test project is now added to your solution:</p>
<div id="attachment_330" class="wp-caption alignnone" style="width: 368px"><img class="size-full wp-image-330" title="TestProject1 project" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs61.jpg?w=358&#038;h=284" alt="TestProject1 project" width="358" height="284" /><p class="wp-caption-text">TestProject1 project</p></div>
<p>Delete the generated UnitTest1.cs file. Also add a reference to the MvcApplication1 project, and to:</p>
<ul>
<li>System.Web.Mvc</li>
<li>System.Web.Abstractions</li>
<li>System.Data</li>
<li>System.Data.DataSetExtensions</li>
<li>System.Web</li>
<li>System.Web.Routing</li>
</ul>
<p>You should test every aspect of you project, in this case this means that you should test:</p>
<ul>
<li>Model (MemberService)</li>
<li>Controller action methods (MemberController)</li>
<li>Routing</li>
</ul>
<h2>Task 2: Test model</h2>
<p>Right click the TestProject1 project and select Add -&gt; New test:</p>
<div id="attachment_332" class="wp-caption alignnone" style="width: 771px"><img class="size-full wp-image-332" title="Add new test" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs62.jpg?w=761&#038;h=642" alt="Add new test" width="761" height="642" /><p class="wp-caption-text">Add new test</p></div>
<p>Select Unit Test and name it ModelTest.cs. Click OK. Add the following using statement on top of the ModelTest class:</p>
<pre><span style="color:#800080;">using MvcApplication1.Models;</span></pre>
<p>Then add some unit tests, like:</p>
<pre><span style="color:#800080;">[TestMethod]
public void Get_Members_Returns_List()
{
    var members = MemberService.GetMembers();
    Assert.IsNotNull(members, "No members retrieved");
    Assert.AreEqual(5, members.Count, "Got wrong number of members");
    Assert.AreEqual("Geoffrey", members[0].FirstName);
    Assert.AreEqual("Denver", members[0].LastName);
    // ...
}</span>
<span style="color:#800080;">[TestMethod]
public void Delete_Member_Workd()
{
    var members_before = MemberService.GetMembers();
    MemberService.DeleteMember(members_before[0].ID);
    var members_after = MemberService.GetMembers();</span>
<span style="color:#800080;">    Assert.AreEqual(4, members_after.Count, "Member was not deleted");           
    // ...
}</span></pre>
<p>Run these tests and make sure they pass.</p>
<h2>Task 3: Test controller</h2>
<p>Add a new unit test to the test project and call it MembersControllerTest. Add the following using statements on top:</p>
<pre><span style="color:#800080;">using MvcApplication1.Controllers;
using MvcApplication1.Models;
using System.Web.Mvc;</span></pre>
<p>Add the following tests:</p>
<pre><span style="color:#800080;">[TestMethod]
public void Index_Presents_Correct_Page_Of_Members()
{
    MembersController membersController = new MembersController();
    ViewResult result = membersController.Index() as ViewResult;
       
    Assert.IsNotNull(result, "Didn't render view");
    var members = (IList&lt;Member&gt;)result.ViewData.Model;
    Assert.AreEqual(5, members.Count, "Got wrong number of members");
    Assert.AreEqual("Geoffrey", members[0].FirstName);
    Assert.AreEqual("Denver", members[0].LastName);
}</span>
<span style="color:#800080;">[TestMethod]
public void Details_Presents_Correct_Page_Of_Member()
{
    MembersController membersController = new MembersController();
    ViewResult result = membersController.Details(0) as ViewResult;</span>
<span style="color:#800080;">    Assert.IsNotNull(result, "Didn't render view");
    var member = ((Member)result.ViewData.Model);           
    Assert.AreEqual("Geoffrey", member.FirstName);
    Assert.AreEqual("Denver", member.LastName);
}</span></pre>
<p>Run these tests and make sure they pass.</p>
<h2>Task 4: Test routing</h2>
<p>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 <a href="http://code.google.com/p/moq">http://code.google.com/p/moq</a>. Then, from the unit test project, add a reference to Moq.dll.</p>
<p>Add a new unit test and call it InboundRoutingTests.cs. On top of this class, add the following using statements:</p>
<pre><span style="color:#800080;">using System.Web.Routing;
using MvcApplication1;
using System.Web;</span></pre>
<p>Testing a specific route comes always down to the same:</p>
<ul>
<li>registering the web application’s route collection</li>
<li>mocking the request context</li>
<li>get the mapped route based in the URL</li>
<li>test the mapped route to see if it matches expected values</li>
</ul>
<p>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:</p>
<pre><span style="color:#800080;">private void TestRoute(string url, object expectedValues)
{
    // Arrange: Prepare the route collection and a mock request context
    RouteCollection routes = new RouteCollection();
    MvcApplication.RegisterRoutes(routes);
    var mockHttpContext = new Moq.Mock&lt;HttpContextBase&gt;();
    var mockRequest = new Moq.Mock&lt;HttpRequestBase&gt;();
    mockHttpContext.Setup(x =&gt; x.Request).Returns(mockRequest.Object);
    mockRequest.Setup(x =&gt;
            x.AppRelativeCurrentExecutionFilePath).Returns(url);</span>
<span style="color:#800080;">    // Act: Get the mapped route
    RouteData routeData = routes.GetRouteData(mockHttpContext.Object);</span>
<span style="color:#800080;">    // Assert: Test the route values against expectations
    Assert.IsNotNull(routeData);
    var expectedDict = new RouteValueDictionary(expectedValues);
    foreach (var expectedVal in expectedDict)
    {
        if (expectedVal.Value == null)
            Assert.IsNull(routeData.Values[expectedVal.Key]);
        else
            Assert.AreEqual(expectedVal.Value.ToString(),
                                     
        routeData.Values[expectedVal.Key].ToString());
    }
}</span></pre>
<p>And finally we can write unit tests to test different routes, for example:</p>
<pre><span style="color:#800080;">[TestMethod]
public void Slash_Goes_To_All_Members_Page()
{
    TestRoute("~/", new
    {
        controller = "Home",
        action = "Index",
        id = (string)null,               
    });
}</span>
<span style="color:#800080;">[TestMethod]
public void Member2_Goes_To_Member2_Details_Page()
{
    TestRoute("~/member2", new
    {
        controller = "Members",
        action = "Details",
        id = 2,
    });
}</span></pre>
<p>Run these tests and make sure they pass.</p>
<p>Go to <a href="http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-7-action-filters/" target="_self">next part</a>.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ludwigstuyck.wordpress.com/328/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ludwigstuyck.wordpress.com/328/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ludwigstuyck.wordpress.com/328/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ludwigstuyck.wordpress.com/328/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ludwigstuyck.wordpress.com/328/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ludwigstuyck.wordpress.com/328/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ludwigstuyck.wordpress.com/328/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ludwigstuyck.wordpress.com/328/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ludwigstuyck.wordpress.com/328/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ludwigstuyck.wordpress.com/328/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=328&subd=ludwigstuyck&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-6-automated-testing/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2417489f4fa437ef00401ab389ffbe9a?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">Ludwig Stuyck</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs60.jpg" medium="image">
			<media:title type="html">Add new project</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs61.jpg" medium="image">
			<media:title type="html">TestProject1 project</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs62.jpg" medium="image">
			<media:title type="html">Add new test</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC QuickStart 5: routing</title>
		<link>http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-5-routing/</link>
		<comments>http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-5-routing/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 08:30:08 +0000</pubDate>
		<dc:creator>Ludwig Stuyck</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://ludwigstuyck.wordpress.com/?p=315</guid>
		<description><![CDATA[&#8230;continued from part 4.
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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=315&subd=ludwigstuyck&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>&#8230;continued from <a href="http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-4-implement-validation/" target="_self">part 4</a>.</p>
<h2>Objectives</h2>
<p>In this Hands-On Lab, you will be introduced to the ASP.NET MVC framework. In particular, you will:</p>
<ul>
<li>Task 1: Understand routing</li>
<li>Task 2: Add constraint</li>
<li>Task 3: Add new route</li>
<li>Task 4: Generate outgoing URL’s</li>
</ul>
<h2>System requirements</h2>
<p>You must have the following items to complete this lab:</p>
<ul>
<li>Microsoft Visual Studio 2008 SP1 (professional edition)</li>
<li>Microsoft ASP.NET MVC 1.0</li>
</ul>
<h2>Prequisites</h2>
<p>You must have the following skills to understand this lab:</p>
<ul>
<li>Fundamental knowledge of software development in .NET 3.5</li>
<li>Some experience in ASP.NET web development</li>
</ul>
<p>This lab builds further on the QuickStart 4 code.</p>
<h2>Task 1: understand routing</h2>
<p>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:</p>
<pre><span style="color:#800080;">public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");</span>
<span style="color:#800080;">    routes.MapRoute(
        "Default",                              // Route name
        "{controller}/{action}/{id}",           // URL with parameters
        new { controller = "Home",
              action = "Index",
              id = "" }                         // Parameter defaults
    );
}</span></pre>
<p>Note: the routing system not only maps incoming URL’S to the appropriate controller/action, but also constructs outgoing URLS!</p>
<p>Each route defines an URL pattern and how to handle requests for such URL’s. For the default route, this means:</p>
<pre><strong>URL                                 Maps to</strong>
/                                   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”</pre>
<p>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.</p>
<p>When you define a route by using the MapRoute method, you can pass a number of parameters:</p>
<ul>
<li>a route name, which is optional</li>
<li>the URL pattern, using parameters</li>
<li>default values: default value for each parameter (optional)</li>
<li>constraints: constraints for each parameter (optional)</li>
</ul>
<h2> Task 2: Add constraint</h2>
<p>If you use <a href="http://localhost:3382/members/Details/2">http://localhost:3382/members/Details/2</a> 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.</p>
<p>However, <a href="http://localhost:3382/members/Details/a">http://localhost:3382/members/Details/a</a> also matches the URL pattern &#8220;{controller}/{action}/{id}&#8221; and so ‘a’ will be mapped to the id parameter. But, id is of type int, and so you will get the error:</p>
<div id="attachment_317" class="wp-caption alignnone" style="width: 876px"><img class="size-full wp-image-317" title="Server error" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs50.jpg?w=866&#038;h=751" alt="Server error" width="866" height="751" /><p class="wp-caption-text">Server error</p></div>
<p>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:</p>
<pre><span style="color:#800080;">routes.MapRoute(
      "Default",                          // Route name
      "{controller}/{action}/{id}",       // URL with parameters
      new { controller = "Home",
            action = "Index",
            id = 0 },                     // Parameter defaults
      new { id = @"\d{1,6}" }             // Constraints
);</span></pre>
<p>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 <a href="http://localhost:3382/members/Details/a">http://localhost:3382/members/Details/a</a> isn’t mapped:</p>
<div id="attachment_319" class="wp-caption alignnone" style="width: 876px"><img class="size-full wp-image-319" title="Server error" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs51.jpg?w=866&#038;h=826" alt="Server error" width="866" height="826" /><p class="wp-caption-text">Server error</p></div>
<h2>Task 3: Add new route</h2>
<p>Suppose we want the following URL to work:</p>
<pre><strong>URL                          Maps to</strong>
/member1                     controller = Members, action = Details, id = “1”
/member3                     controller = Members, action = Details, id = “3”</pre>
<p>If you try that, obviously it does not match any URL pattern yet, so you’ll get an error:</p>
<div id="attachment_320" class="wp-caption alignnone" style="width: 877px"><img class="size-full wp-image-320" title="Server error" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs52.jpg?w=867&#038;h=789" alt="Server error" width="867" height="789" /><p class="wp-caption-text">Server error</p></div>
<p>To make this work, add a new route to the global.asax.cs file (it has to be the first one):</p>
<pre><span style="color:#888888;">public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");</span>
<span style="color:#888888;">    <span style="color:#800080;">routes.MapRoute(
      "",                                  // Route name
      "member{id}",                        // URL with parameters
      new { controller = "Members",
            action = "Details",
            id = 0 },                      // Parameter defaults
      new { id = @"\d{1,6}" }              // Constraints
            );</span></span>
<span style="color:#888888;">    routes.MapRoute(
      "Default",                           // Route name
      "{controller}/{action}/{id}",        // URL with parameters
      new { controller = "Home",
      action = "Index",
     id = 0 },                             // Parameter defaults
     new { id = @"\d{1,6}" }               // Constraints
            );                      
}</span></pre>
<p>Note: add routes in the correct order: from most specific to least specific!</p>
<p>Now try <a href="http://localhost:3382/member3">http://localhost:3382/member3</a>:</p>
<div id="attachment_322" class="wp-caption alignnone" style="width: 876px"><img class="size-full wp-image-322" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs53.jpg?w=866&#038;h=786" alt="My MVC application" width="866" height="786" /><p class="wp-caption-text">My MVC application</p></div>
<h2>Task 4: Generate outgoing URL’s</h2>
<p>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.</p>
<p>In previous examples we already used Html.ActionLink to construct the links to view, create, edit and delete members, for example:</p>
<pre><span style="color:#800080;">&lt;%= Html.ActionLink("Details", "Details", new { id = item.ID })%&gt;</span></pre>
<p>This generated the links as follows:</p>
<div id="attachment_323" class="wp-caption alignnone" style="width: 842px"><img class="size-full wp-image-323" title="Generated links" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs54.jpg?w=832&#038;h=315" alt="Generated links" width="832" height="315" /><p class="wp-caption-text">Generated links</p></div>
<p>However, in task 3 we added a new route to view the details of a member, so that URL’s in the form of <a href="http://localhost:3382/member3">http://localhost:3382/member3</a> work. After adding this route, the generated URL’s look different:</p>
<div id="attachment_324" class="wp-caption alignnone" style="width: 806px"><img class="size-full wp-image-324" title="Generated links" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs55.jpg?w=796&#038;h=318" alt="Generated links" width="796" height="318" /><p class="wp-caption-text">Generated links</p></div>
<p>This is because Html.ActionLink uses the routing configuration to construct the URL’s.</p>
<p>Note: If we would have constructed the links hard coded, changing routing configuration may have broken those links!</p>
<p>Go to <a href="http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-6-automated-testing/" target="_self">next part</a>.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ludwigstuyck.wordpress.com/315/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ludwigstuyck.wordpress.com/315/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ludwigstuyck.wordpress.com/315/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ludwigstuyck.wordpress.com/315/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ludwigstuyck.wordpress.com/315/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ludwigstuyck.wordpress.com/315/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ludwigstuyck.wordpress.com/315/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ludwigstuyck.wordpress.com/315/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ludwigstuyck.wordpress.com/315/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ludwigstuyck.wordpress.com/315/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=315&subd=ludwigstuyck&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-5-routing/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2417489f4fa437ef00401ab389ffbe9a?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">Ludwig Stuyck</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs50.jpg" medium="image">
			<media:title type="html">Server error</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs51.jpg" medium="image">
			<media:title type="html">Server error</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs52.jpg" medium="image">
			<media:title type="html">Server error</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs53.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs54.jpg" medium="image">
			<media:title type="html">Generated links</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs55.jpg" medium="image">
			<media:title type="html">Generated links</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC QuickStart 4: implement validation</title>
		<link>http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-4-implement-validation/</link>
		<comments>http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-4-implement-validation/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 07:56:45 +0000</pubDate>
		<dc:creator>Ludwig Stuyck</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://ludwigstuyck.wordpress.com/?p=302</guid>
		<description><![CDATA[&#8230; continued from part 3.
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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=302&subd=ludwigstuyck&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>&#8230; continued from <a href="http://ludwigstuyck.wordpress.com/2009/06/10/asp-net-mvc-quickstart-3-implement-details-create-edit-and-delete-functionality/" target="_self">part 3</a>.</p>
<h2>Objectives</h2>
<p>In this Hands-On Lab, you will create functionality to add validation of members. In particular, you will:</p>
<ul>
<li>Task 1: understand validation</li>
<li>Task 2: add convenience method to ModelState</li>
<li>Task 3: implement validation logic in model</li>
<li>Task 4: handle validation errors in controller</li>
</ul>
<h2>System requirements</h2>
<p>You must have the following items to complete this lab:</p>
<ul>
<li>Microsoft Visual Studio 2008 SP1 (professional edition)</li>
<li>Microsoft ASP.NET MVC 1.0</li>
</ul>
<h2>Prequisites</h2>
<p>You must have the following skills to understand this lab:</p>
<ul>
<li>Fundamental knowledge of software development in .NET 3.5</li>
<li>Some experience in ASP.NET web development</li>
</ul>
<p>This lab builds further on the QuickStart 3 code.</p>
<h2>Task 1: understand validation</h2>
<p>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.</p>
<p>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.</p>
<p>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:</p>
<ul>
<li>Controller asks model to do validation and if validation fails, it receives the list of validation errors from the model.</li>
<li>Controller registers the validation errors in ModelState, by calling the ModelState.AddModelError method for each error. This will add all errors to the ModelStateDictionary.</li>
<li>The view has access to this ModelStateDictionary and you can use Html helper methods to display the information:
<ul>
<li>Html.ValidationSummary: returns a list of validation errors.</li>
<li>Html.ValidationMessage: returns validation message for specific field.</li>
</ul>
</li>
</ul>
<h2>Task 2: add convenience method to ModelState</h2>
<p>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.</p>
<p>Right click the web project MvcApplication1, and select Add -&gt; New folder, and call it Helpers. Then right click the Helpers folder and select Add -&gt; Class, and call it ModelStateHelpers.cs. Write the extension method as follows:</p>
<pre><span style="color:#800080;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcApplication1.Models;
using System.Web.Mvc;</span>
<span style="color:#800080;">namespace MvcApplication1.Helpers
{
    public static class ModelStateHelpers
    {
        public static void AddModelErrors(
                     this ModelStateDictionary modelState,
                     IEnumerable&lt;RuleViolation&gt; errors)
        {
            foreach (RuleViolation issue in errors)
            {
                modelState.AddModelError(
                         issue.PropertyName, issue.ErrorMessage);
            }
        }
    }
}</span></pre>
<h2>Task 3: implement validation logic in model</h2>
<p>Now we will create the validation logic in our model.</p>
<p>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:</p>
<pre><span style="color:#800080;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;</span>
<span style="color:#800080;">namespace MvcApplication1.Models
{
    public class RuleViolation
    {
        public string ErrorMessage { get; private set; }
        public string PropertyName { get; private set; }</span>
<span style="color:#800080;">        public RuleViolation(string errorMessage)
        {
            ErrorMessage = errorMessage;
        }</span>
<span style="color:#800080;">        public RuleViolation(string errorMessage, string propertyName)
        {
            ErrorMessage = errorMessage;
            PropertyName = propertyName;
        }
    }
}</span></pre>
<p>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:</p>
<pre><span style="color:#800080;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;</span>
<span style="color:#800080;">namespace MvcApplication1.Models
{
    public class RuleException : Exception
    {
        public IEnumerable&lt;RuleViolation&gt;
                     RuleViolations { get; private set; }</span>
<span style="color:#800080;">        public RuleException(IEnumerable&lt;RuleViolation&gt; ruleViolations)
        {
            RuleViolations = ruleViolations;
        }       
    }   
}</span></pre>
<p>Now it’s time to do the actual validation. Add the following two methods to the Member class in the Models folder:</p>
<pre><span style="color:#800080;">public bool IsValid
{
    get { return (GetRuleViolations().Count() == 0); }
}</span>
<span style="color:#800080;">public IEnumerable&lt;RuleViolation&gt; GetRuleViolations()
{
    if (String.IsNullOrEmpty(FirstName))
        yield return new RuleViolation(
                    "First name is required", "FirstName");</span>
<span style="color:#800080;">    if (String.IsNullOrEmpty(LastName))
        yield return new RuleViolation(
                    "Last name is required", "LastName");</span>
<span style="color:#800080;">    yield break;
}</span></pre>
<p>To keep things simple we demand that first name and last name have to be filled in.</p>
<p>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:</p>
<pre><span style="color:#800080;"><span style="color:#808080;">public static void CreateMember(Member member)
{
</span>    if (!member.IsValid)
        throw new RuleException(member.GetRuleViolations());</span>
<span style="color:#800080;">    <span style="color:#808080;">// Set member id to next free id
    member.ID = members.Max(m =&gt; m.ID) + 1;
    // add member to collection
    members.Add(member);
}</span></span></pre>
<p>And do the same in the UpdateMember method:</p>
<pre><span style="color:#808080;">public static void UpdateMember(Member member)
{
    <span style="color:#800080;">if (!member.IsValid)
        throw new RuleException(member.GetRuleViolations());</span></span>
<span style="color:#808080;">    // Find member in collection
    Member foundMember = members.Find(m =&gt; m.ID == member.ID);
    // Update member
    foundMember.FirstName = member.FirstName;
    foundMember.LastName = member.LastName;
}</span></pre>
<p>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.</p>
<h2>Task 4: handle validation errors in controller</h2>
<p>Modify code of the Create action method in the MembersController class as follows:</p>
<pre><span style="color:#800080;">[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Member member)
{
    try
    {
        // Use model to create this new member
        MemberService.CreateMember(member);
        // Redirect to Details action method and pass the new id
        return RedirectToAction("Details", new { id = member.ID });
    }
    catch (RuleException ex)
    {
        ModelState.AddModelErrors(ex.RuleViolations);
        return View(member);
    }
}</span></pre>
<p>And do the same for the Update action method:</p>
<pre><span style="color:#800080;">[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Member member)
{           
    try
    {
        // Use model to create this new member
        MemberService.CreateMember(member);
        // Redirect to Details action method and pass the new id
        return RedirectToAction("Details", new { id = member.ID });
    }
    catch (RuleException ex)
    {
        ModelState.AddModelErrors(ex.RuleViolations);
        return View(member);
    }
}</span></pre>
<p>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:</p>
<pre><span style="color:#800080;">using MvcApplication1.Helpers;</span></pre>
<p>Right, let’s test this. Start the web application, and create a new member but don’t fill in last name:</p>
<div id="attachment_306" class="wp-caption alignnone" style="width: 874px"><img class="size-full wp-image-306" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs40.jpg?w=864&#038;h=863" alt="My MVC application" width="864" height="863" /><p class="wp-caption-text">My MVC application</p></div>
<p>Click Create.</p>
<div id="attachment_308" class="wp-caption alignnone" style="width: 874px"><img class="size-full wp-image-308" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs411.jpg?w=864&#038;h=875" alt="My MVC application" width="864" height="875" /><p class="wp-caption-text">My MVC application</p></div>
<p>The validation does its work and validation errors are displayed. But why does it also display the ‘A value is required’ message?</p>
<p>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.</p>
<p>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:</p>
<pre><span style="color:#888888;"><span style="color:#800080;">[Bind(Include = "FirstName,LastName")]
</span>public class Member
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }</span>
<span style="color:#888888;">    …
}</span></pre>
<p>Now only FirstName and LastName properties are bound and validated; and so ID is not validated anymore:</p>
<div id="attachment_310" class="wp-caption alignnone" style="width: 876px"><img class="size-full wp-image-310" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs42.jpg?w=866&#038;h=891" alt="My MVC application" width="866" height="891" /><p class="wp-caption-text">My MVC application</p></div>
<div class="mceTemp">Go to <a href="http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-5-routing/" target="_self">next part</a>.</div>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ludwigstuyck.wordpress.com/302/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ludwigstuyck.wordpress.com/302/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ludwigstuyck.wordpress.com/302/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ludwigstuyck.wordpress.com/302/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ludwigstuyck.wordpress.com/302/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ludwigstuyck.wordpress.com/302/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ludwigstuyck.wordpress.com/302/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ludwigstuyck.wordpress.com/302/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ludwigstuyck.wordpress.com/302/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ludwigstuyck.wordpress.com/302/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=302&subd=ludwigstuyck&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-4-implement-validation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2417489f4fa437ef00401ab389ffbe9a?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">Ludwig Stuyck</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs40.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs411.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs42.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC QuickStart 3: Implement details, create, edit and delete functionality</title>
		<link>http://ludwigstuyck.wordpress.com/2009/06/10/asp-net-mvc-quickstart-3-implement-details-create-edit-and-delete-functionality/</link>
		<comments>http://ludwigstuyck.wordpress.com/2009/06/10/asp-net-mvc-quickstart-3-implement-details-create-edit-and-delete-functionality/#comments</comments>
		<pubDate>Wed, 10 Jun 2009 14:15:41 +0000</pubDate>
		<dc:creator>Ludwig Stuyck</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://ludwigstuyck.wordpress.com/?p=263</guid>
		<description><![CDATA[&#8230;continued from part 2.
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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=263&subd=ludwigstuyck&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>&#8230;continued from <a href="http://ludwigstuyck.wordpress.com/2009/06/10/asp-net-mvc-quickstart-2-implement-model-controller-and-view/" target="_self">part 2</a>.</p>
<h2>Objectives</h2>
<p>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:</p>
<ul>
<li>Task 1: making the Details link work</li>
<li>Task 2: making the Create New link work</li>
<li>Task 3: making the Edit link work</li>
<li>Task 4: making the Delete link work</li>
<li>Task 5: adding validation</li>
</ul>
<h2>System requirements</h2>
<p>You must have the following items to complete this lab:</p>
<ul>
<li>Microsoft Visual Studio 2008 SP1 (professional edition)</li>
<li>Microsoft ASP.NET MVC 1.0</li>
</ul>
<h2>Prequisites</h2>
<p>You must have the following skills to understand this lab:</p>
<ul>
<li>Fundamental knowledge of software development in .NET 3.5</li>
<li>Some experience in ASP.NET web development</li>
</ul>
<p>This lab builds further on the QuickStart 2 code.</p>
<h2>Task 1: making the Details link work</h2>
<p>When you click on the Details link, you would expect to see a page with the details of that specific member.</p>
<p>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):</p>
<div id="attachment_265" class="wp-caption alignnone" style="width: 507px"><img class="size-full wp-image-265" title="Details link" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs20.jpg?w=497&#038;h=194" alt="Details link" width="497" height="194" /><p class="wp-caption-text">Details link</p></div>
<p>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.</p>
<p>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:</p>
<pre><span style="color:#800080;">public static Member GetMember(int id)
{
    return members.Find(m =&gt; m.ID == id);
}</span></pre>
<p>This simply uses a lambda expression to find the member with specified id in the members collection.</p>
<p>Now we will create the controller action: open the MembersController class in the Controllers folder and add the following method:</p>
<pre><span style="color:#800080;">public ActionResult Details(int id)
{
    // Get member details for the specified member id
    Member member = MemberService.GetMember(id);</span>
<span style="color:#800080;">    // return this member to the default view
    return View(member);
}</span></pre>
<p>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:</p>
<div id="attachment_266" class="wp-caption alignnone" style="width: 504px"><img class="size-full wp-image-266" title="Add view" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs21.jpg?w=494&#038;h=545" alt="Add view" width="494" height="545" /><p class="wp-caption-text">Add view</p></div>
<p>Make sure that:</p>
<ul>
<li>The View name is called Details.</li>
<li>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.</li>
<li>Select Details as the View content. This will generate code that displays the details of a member.</li>
</ul>
<p>Click Add. As a result, a Details.aspx view is added to the Views/Members folder:</p>
<pre><span style="color:#800080;">&lt;%@ Page Title="" Language="C#"
         MasterPageFile="~/Views/Shared/Site.Master"
         Inherits="System.Web.Mvc.ViewPage&lt;
                      MvcApplication1.Models.Member&gt;" %&gt;</span>
<span style="color:#800080;">&lt;asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"
             runat="server"&gt;
 Details
&lt;/asp:Content&gt;</span>
<span style="color:#800080;">&lt;asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
             runat="server"&gt;</span>
<span style="color:#800080;">    &lt;h2&gt;Details&lt;/h2&gt;</span>
<span style="color:#800080;">    &lt;fieldset&gt;
        &lt;legend&gt;Fields&lt;/legend&gt;
        &lt;p&gt;
            ID:
            &lt;%= Html.Encode(Model.ID) %&gt;
        &lt;/p&gt;
        &lt;p&gt;
            FirstName:
            &lt;%= Html.Encode(Model.FirstName) %&gt;
        &lt;/p&gt;
        &lt;p&gt;
            LastName:
            &lt;%= Html.Encode(Model.LastName) %&gt;
        &lt;/p&gt;
    &lt;/fieldset&gt;
    &lt;p&gt;
        &lt;%=Html.ActionLink("Edit", "Edit", new
                      { /* id=Model.PrimaryKey */ }) %&gt; |
        &lt;%=Html.ActionLink("Back to List", "Index") %&gt;
    &lt;/p&gt;</span>
<span style="color:#800080;">&lt;/asp:Content&gt;</span></pre>
<p>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:</p>
<pre><span style="color:#800080;">&lt;%= Html.ActionLink("Edit", "Edit", new { id=Model.ID }) %&gt; |</span></pre>
<p>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 <a href="http://localhost:3382/members/index">http://localhost:3382/members/index</a> 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:</p>
<div id="attachment_268" class="wp-caption alignnone" style="width: 516px"><img class="size-full wp-image-268" title="Breakpoint" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs22.jpg?w=506&#038;h=152" alt="Breakpoint" width="506" height="152" /><p class="wp-caption-text">Breakpoint</p></div>
<p>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:</p>
<div id="attachment_270" class="wp-caption alignnone" style="width: 506px"><img class="size-full wp-image-270" title="Model binding" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs23.jpg?w=496&#038;h=249" alt="Model binding" width="496" height="249" /><p class="wp-caption-text">Model binding</p></div>
<p>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:</p>
<div id="attachment_271" class="wp-caption alignnone" style="width: 510px"><img class="size-full wp-image-271" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs24.jpg?w=500&#038;h=522" alt="My MVC application" width="500" height="522" /><p class="wp-caption-text">My MVC application</p></div>
<p>Note: The Back To List link already works, because it was implemented for us:</p>
<pre><span style="color:#800080;">&lt;%=Html.ActionLink("Back to List", "Index") %&gt;</span></pre>
<h2>Task 2: making the Create New link work</h2>
<p>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:</p>
<pre><span style="color:#800080;">public static void CreateMember(Member member)
{
    // Set member id to next free id
    member.ID = members.Max(m =&gt; m.ID) + 1;
    // add member to collection
    members.Add(member);
}</span></pre>
<p>This method takes care of adding a new member to the collection and making sure it gets a valid id.</p>
<p>Then, in the Index.aspx view in the Views/Members folder, the Create New link looks like:</p>
<pre><span style="color:#800080;">&lt;%= Html.ActionLink("Create New", "Create") %&gt;</span></pre>
<p>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):</p>
<pre><span style="color:#800080;">public ActionResult Create()
{
    return View();
}</span></pre>
<p>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:</p>
<div id="attachment_273" class="wp-caption alignnone" style="width: 502px"><img class="size-full wp-image-273" title="Add view" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs25.jpg?w=492&#038;h=532" alt="Add view" width="492" height="532" /><p class="wp-caption-text">Add view</p></div>
<p>Make sure that:</p>
<ul>
<li>The View name is called Create.</li>
<li>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.</li>
<li>Select Create as the View content. This will generate code that displays the creation of a member.</li>
</ul>
<p>Click Add and a new view called Create.aspx will be added to the Views/Members folder:</p>
<pre><span style="color:#800080;">&lt;%@ Page Title="" Language="C#"
         MasterPageFile="~/Views/Shared/Site.Master" 
         Inherits="System.Web.Mvc.ViewPage&lt;
                          MvcApplication1.Models.Member&gt;" %&gt;</span>
<span style="color:#800080;">&lt;asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"
             runat="server"&gt;
 Create
&lt;/asp:Content&gt;</span>
<span style="color:#800080;">&lt;asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
             runat="server"&gt;</span>
<span style="color:#800080;">    &lt;h2&gt;Create&lt;/h2&gt;</span>
<span style="color:#800080;">    &lt;%= Html.ValidationSummary("Create was unsuccessful. Please correct
                                the errors and try again.") %&gt;</span>
<span style="color:#800080;">    &lt;% using (Html.BeginForm()) {%&gt;</span>
<span style="color:#800080;">        &lt;fieldset&gt;
            &lt;legend&gt;Fields&lt;/legend&gt;
            &lt;p&gt;
                &lt;label for="ID"&gt;ID:&lt;/label&gt;
                &lt;%= Html.TextBox("ID") %&gt;
                &lt;%= Html.ValidationMessage("ID", "*") %&gt;
            &lt;/p&gt;
            &lt;p&gt;
                &lt;label for="FirstName"&gt;FirstName:&lt;/label&gt;
                &lt;%= Html.TextBox("FirstName") %&gt;
                &lt;%= Html.ValidationMessage("FirstName", "*") %&gt;
            &lt;/p&gt;
            &lt;p&gt;
                &lt;label for="LastName"&gt;LastName:&lt;/label&gt;
                &lt;%= Html.TextBox("LastName") %&gt;
                &lt;%= Html.ValidationMessage("LastName", "*") %&gt;
            &lt;/p&gt;
            &lt;p&gt;
                &lt;input type="submit" value="Create" /&gt;
            &lt;/p&gt;
        &lt;/fieldset&gt;</span>
<span style="color:#800080;">    &lt;% } %&gt;</span>
<span style="color:#800080;">    &lt;div&gt;
        &lt;%=Html.ActionLink("Back to List", "Index") %&gt;
    &lt;/div&gt;</span>
<span style="color:#800080;">&lt;/asp:Content&gt;</span></pre>
<p>To try this view, run the application, go to <a href="http://localhost:3382/members/index">http://localhost:3382/members/index</a> and click the Create New link. Or, immediately type in the url <a href="http://localhost:3382/members/Create">http://localhost:3382/members/Create</a>:</p>
<div id="attachment_274" class="wp-caption alignnone" style="width: 503px"><img class="size-full wp-image-274" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs26.jpg?w=493&#038;h=541" alt="My MVC application" width="493" height="541" /><p class="wp-caption-text">My MVC application</p></div>
<p>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.</p>
<div id="attachment_275" class="wp-caption alignnone" style="width: 508px"><img class="size-full wp-image-275" title="Delete part" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs27.jpg?w=498&#038;h=191" alt="Delete part" width="498" height="191" /><p class="wp-caption-text">Delete part</p></div>
<p>This view uses the Html.TextBox helper to generate textboxes to fill in the required data.</p>
<p>Also notice the Html.BeginForm statement:</p>
<pre><span style="color:#800080;">&lt;% using (Html.BeginForm()) {%&gt;</span></pre>
<p>which will generate a form-element:</p>
<pre><span style="color:#800080;">&lt;form action=”/members/Create” method=”post”&gt;&lt;/form&gt;</span></pre>
<p>So, when the Create button is clicked (which is of input type submit), a new POST request to <a href="http://localhost/members/create">http://localhost/members/create</a> 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?</p>
<p>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:</p>
<pre><span style="color:#800080;">[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Create()
{
    return View();
}</span></pre>
<p>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.</p>
<p>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.</p>
<pre><span style="color:#800080;">[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Member member)
{
    // Use model to create this new member
    MemberService.CreateMember(member);
    // Redirect to Details action method and pass the new id
    return RedirectToAction("Details", new { id = member.ID });
}</span></pre>
<p>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).</p>
<p>Previously we already wrote this Details action method, so it will already work: when the new member is created, its details will be shown.</p>
<p>Test it: run the application, and create a new member:</p>
<div id="attachment_277" class="wp-caption alignnone" style="width: 511px"><img class="size-full wp-image-277" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs28.jpg?w=501&#038;h=551" alt="My MVC application" width="501" height="551" /><p class="wp-caption-text">My MVC application</p></div>
<p>When you click Create, the member will be created and you will be redirected to the details view:</p>
<div id="attachment_278" class="wp-caption alignnone" style="width: 508px"><img class="size-full wp-image-278" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs29.jpg?w=498&#038;h=546" alt="My MVC application" width="498" height="546" /><p class="wp-caption-text">My MVC application</p></div>
<p>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:</p>
<div id="attachment_279" class="wp-caption alignnone" style="width: 506px"><img class="size-full wp-image-279" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs30.jpg?w=496&#038;h=541" alt="My MVC application" width="496" height="541" /><p class="wp-caption-text">My MVC application</p></div>
<h2>Task 3: making the Edit link work</h2>
<p>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:</p>
<pre><span style="color:#800080;">public static void UpdateMember(Member member)
{
    // Find member in collection
    Member foundMember = members.Find(m =&gt; m.ID == member.ID);
    // Update member
    foundMember.FirstName = member.FirstName;
    foundMember.LastName = member.LastName;
}</span></pre>
<p>The Edit link in the Index.aspx view looked like:</p>
<pre><span style="color:#800080;">&lt;%= Html.ActionLink("Edit", "Edit", new { id=item.ID }) %&gt;</span></pre>
<p>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):</p>
<pre><span style="color:#800080;">[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Edit(int id)
{
    // Get member details using model
    Member member = MemberService.GetMember(id);
    // Return default view and pass member
    return View(member);
}</span></pre>
<p>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:</p>
<div id="attachment_281" class="wp-caption alignnone" style="width: 510px"><img class="size-full wp-image-281" title="Add view" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs31.jpg?w=500&#038;h=542" alt="Add view" width="500" height="542" /><p class="wp-caption-text">Add view</p></div>
<p>Make sure that:</p>
<ul>
<li>The View name is called Edit.</li>
<li>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.</li>
<li>Select Edit as the View content. This will generate code that displays the editing of a member.</li>
</ul>
<p>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:</p>
<div id="attachment_282" class="wp-caption alignnone" style="width: 505px"><img class="size-full wp-image-282" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs32.jpg?w=495&#038;h=542" alt="My MVC application" width="495" height="542" /><p class="wp-caption-text">My MVC application</p></div>
<p>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.</p>
<p>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:</p>
<pre><span style="color:#800080;">[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Member member)
{
    // Use model to update this existing member
    MemberService.UpdateMember(member);
    // Redirect to Details action method and pass the id
    return RedirectToAction("Details", new { id = member.ID });
}</span></pre>
<p>Run the application again, and rename Loren Lyle to Laura Lyle:</p>
<div id="attachment_283" class="wp-caption alignnone" style="width: 505px"><img class="size-full wp-image-283" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs33.jpg?w=495&#038;h=540" alt="My MVC application" width="495" height="540" /><p class="wp-caption-text">My MVC application</p></div>
<p>Click Save:</p>
<div id="attachment_285" class="wp-caption alignnone" style="width: 509px"><img class="size-full wp-image-285" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs34.jpg?w=499&#038;h=550" alt="My MVC application" width="499" height="550" /><p class="wp-caption-text">My MVC application</p></div>
<p>And if you go back to the list, it will also display the new name:</p>
<div id="attachment_286" class="wp-caption alignnone" style="width: 509px"><img class="size-full wp-image-286" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs35.jpg?w=499&#038;h=539" alt="My MVC application" width="499" height="539" /><p class="wp-caption-text">My MVC application</p></div>
<h2>Task 4: making the Delete link work</h2>
<p>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:</p>
<pre><span style="color:#800080;">public static void DeleteMember(int id)
{
    // Find member in collection
    Member memberToDelete = GetMember(id);
    // Delete member
    members.Remove(memberToDelete);
}</span></pre>
<p>There wasn’t a Delete  link in the Index.aspx view yet, so we will add it now:</p>
<div id="attachment_287" class="wp-caption alignnone" style="width: 514px"><img class="size-full wp-image-287" title="Add delete link" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs36.jpg?w=504&#038;h=119" alt="Add delete link" width="504" height="119" /><p class="wp-caption-text">Add delete link</p></div>
<p>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):</p>
<pre><span style="color:#800080;">[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Delete(int id)
{
    // Get member details using model
    Member member = MemberService.GetMember(id);
    // Return default view and pass member
    return View(member);
}</span></pre>
<p>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:</p>
<div id="attachment_289" class="wp-caption alignnone" style="width: 510px"><img class="size-full wp-image-289" title="Add view" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs37.jpg?w=500&#038;h=537" alt="Add view" width="500" height="537" /><p class="wp-caption-text">Add view</p></div>
<p>Make sure that:</p>
<ul>
<li>The View name is called Delete.</li>
<li>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.</li>
<li>Select Empty as the View content. We will add some HTML manually.</li>
</ul>
<p>Click Add, and the Delete.aspx view will be created in the folder Views/Members. Make this view look like:</p>
<pre><span style="color:#800080;">&lt;%@ Page Title="" Language="C#"
         MasterPageFile="~/Views/Shared/Site.Master"
         Inherits="System.Web.Mvc.ViewPage&lt;
                      MvcApplication1.Models.Member&gt;" %&gt;</span>
<span style="color:#800080;">&lt;asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"
             runat="server"&gt;
 Delete
&lt;/asp:Content&gt;</span>
<span style="color:#800080;">&lt;asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
             runat="server"&gt;</span>
<span style="color:#800080;">    &lt;h2&gt;Delete&lt;/h2&gt;
   
    Do you really want to delete &lt;% = Model.FirstName %&gt; &lt;% =
    Model.LastName %&gt;?
   
    &lt;% using (Html.BeginForm(new { id = Model.ID }))
       { %&gt;
       &lt;p&gt;
            &lt;input type="submit" value="Delete" /&gt;
        &lt;/p&gt;
    &lt;% } %&gt;</span>
<span style="color:#800080;">    &lt;div&gt;
        &lt;%=Html.ActionLink("Back to List", "Index") %&gt;
    &lt;/div&gt;</span>
<span style="color:#800080;">&lt;/asp:Content&gt;</span></pre>
<p>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:</p>
<pre><span style="color:#800080;">[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(Member member)
{
    // Use model to delete this existing member
    MemberService.DeleteMember(member.ID);
    // Redirect to Index action method
    return RedirectToAction("Index");
}</span></pre>
<p>That should do it! Run the application, and delete the member Todd Lorn:</p>
<div id="attachment_291" class="wp-caption alignnone" style="width: 508px"><img class="size-full wp-image-291" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs38.jpg?w=498&#038;h=540" alt="My MVC application" width="498" height="540" /><p class="wp-caption-text">My MVC application</p></div>
<p>Click Delete, and the member will be deleted:</p>
<div id="attachment_292" class="wp-caption alignnone" style="width: 508px"><img class="size-full wp-image-292" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs39.jpg?w=498&#038;h=546" alt="My MVC application" width="498" height="546" /><p class="wp-caption-text">My MVC application</p></div>
<p> </p>
<p>Go to <a href="http://ludwigstuyck.wordpress.com/2009/06/15/asp-net-mvc-quickstart-4-implement-validation/" target="_self">next part</a>.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ludwigstuyck.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ludwigstuyck.wordpress.com/263/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ludwigstuyck.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ludwigstuyck.wordpress.com/263/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ludwigstuyck.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ludwigstuyck.wordpress.com/263/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ludwigstuyck.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ludwigstuyck.wordpress.com/263/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ludwigstuyck.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ludwigstuyck.wordpress.com/263/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=263&subd=ludwigstuyck&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ludwigstuyck.wordpress.com/2009/06/10/asp-net-mvc-quickstart-3-implement-details-create-edit-and-delete-functionality/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2417489f4fa437ef00401ab389ffbe9a?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">Ludwig Stuyck</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs20.jpg" medium="image">
			<media:title type="html">Details link</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs21.jpg" medium="image">
			<media:title type="html">Add view</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs22.jpg" medium="image">
			<media:title type="html">Breakpoint</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs23.jpg" medium="image">
			<media:title type="html">Model binding</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs24.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs25.jpg" medium="image">
			<media:title type="html">Add view</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs26.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs27.jpg" medium="image">
			<media:title type="html">Delete part</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs28.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs29.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs30.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs31.jpg" medium="image">
			<media:title type="html">Add view</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs32.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs33.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs34.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs35.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs36.jpg" medium="image">
			<media:title type="html">Add delete link</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs37.jpg" medium="image">
			<media:title type="html">Add view</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs38.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs39.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC QuickStart 2: Implement model, controller and view</title>
		<link>http://ludwigstuyck.wordpress.com/2009/06/10/asp-net-mvc-quickstart-2-implement-model-controller-and-view/</link>
		<comments>http://ludwigstuyck.wordpress.com/2009/06/10/asp-net-mvc-quickstart-2-implement-model-controller-and-view/#comments</comments>
		<pubDate>Wed, 10 Jun 2009 13:15:56 +0000</pubDate>
		<dc:creator>Ludwig Stuyck</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://ludwigstuyck.wordpress.com/?p=240</guid>
		<description><![CDATA[&#8230;continued from part 1.
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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=240&subd=ludwigstuyck&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>&#8230;continued from <a href="http://ludwigstuyck.wordpress.com/2009/06/10/asp-net-mvc-quickstart-1-introducing-asp-net-mvc/" target="_self">part 1</a>.</p>
<h2>Objectives</h2>
<p>In this Hands-On Lab, you will create functionality to display a list of members. In particular, you will:</p>
<ul>
<li>Create a model</li>
<li>Create a controller</li>
<li>Create a view</li>
</ul>
<h2>System requirements</h2>
<p>You must have the following items to complete this lab:</p>
<ul>
<li>Microsoft Visual Studio 2008 SP1 (professional edition)</li>
<li>Microsoft ASP.NET MVC 1.0</li>
</ul>
<h2>Prequisites</h2>
<p>You must have the following skills to understand this lab:</p>
<ul>
<li>Fundamental knowledge of software development in .NET 3.5</li>
<li>Some experience in ASP.NET web development</li>
</ul>
<p>This lab builds further on the QuickStart 1 code.</p>
<h2>Task 1: create a model</h2>
<p>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 -&gt; Class and call the new class Member.cs:</p>
<div id="attachment_241" class="wp-caption alignnone" style="width: 507px"><img class="size-full wp-image-241" title="Add member" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs11.jpg?w=497&#038;h=304" alt="Add member" width="497" height="304" /><p class="wp-caption-text">Add member</p></div>
<p>Keep it simple, and define the following properties:</p>
<pre><span style="color:#800080;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication1.Models
{
    public class Member
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }       
    }
}</span></pre>
<p>The model is also responsible for data access operations, so add another class to the Model folder and call it MemberService.cs:</p>
<pre><span style="color:#800080;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication1.Models
{
    /// &lt;summary&gt;
    /// For simplicity, MemberService mimics a member service providing
    /// basic member operations and working with mock data.
    /// &lt;/summary&gt;
    public class MemberService
    {
        private static List&lt;Member&gt; members;
        static MemberService()
        {
            // Create some dummy members
            members = new List&lt;Member&gt;();
            members.Add(new Member()
              { ID = 0, FirstName = "Geoffrey", LastName = "Denver" });
            members.Add(new Member()
              { ID = 1, FirstName = "Todd", LastName = "Lorn" });
            members.Add(new Member()
              { ID = 2, FirstName = "Loren", LastName = "Lyle" });
            members.Add(new Member()
              { ID = 3, FirstName = "Ralphie", LastName = "Ethan" });
            members.Add(new Member()
              { ID = 4, FirstName = "Mervyn", LastName = "Tyler" });
        }
        public static List&lt;Member&gt; GetMembers()
        {
            return members;
        }
    }
}</span></pre>
<p>At this point, we have created a very basic model that we can use to retrieve members.</p>
<h2>Task 2: create a controller</h2>
<p>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 -&gt; Controller and call it MembersController:</p>
<div id="attachment_242" class="wp-caption alignnone" style="width: 509px"><img class="size-full wp-image-242" title="Add controller" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs12.jpg?w=499&#038;h=200" alt="Add controller" width="499" height="200" /><p class="wp-caption-text">Add controller</p></div>
<p>Click Add. The new file membersController.cs will now be added to the Controllers folder. Modify it as follows:</p>
<pre><span style="color:#800080;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
    public class MembersController : Controller
    {
        //
        // GET: /Members/
        public ActionResult Index()
        {
            // Get a list of members using the model
            List&lt;Member&gt; members = MemberService.GetMembers();
           
            // return this list to the default view
            return View(members);
        }
    }
}</span></pre>
<p>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:</p>
<div id="attachment_244" class="wp-caption alignnone" style="width: 509px"><img class="size-full wp-image-244" title="Debugging not enabled" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs13.jpg?w=499&#038;h=213" alt="Debugging not enabled" width="499" height="213" /><p class="wp-caption-text">Debugging not enabled</p></div>
<p>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:</p>
<div id="attachment_245" class="wp-caption alignnone" style="width: 515px"><img class="size-full wp-image-245" title="Web page" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs14.jpg?w=505&#038;h=125" alt="Web page" width="505" height="125" /><p class="wp-caption-text">Web page</p></div>
<div class="mceTemp"> </div>
<div class="mceTemp">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:</div>
<div class="mceTemp"> </div>
<div class="mceTemp">
<div id="attachment_247" class="wp-caption alignnone" style="width: 520px"><img class="size-full wp-image-247" title="MembersController" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs15.jpg?w=510&#038;h=271" alt="MembersController" width="510" height="271" /><p class="wp-caption-text">MembersController</p></div>
</div>
<div class="mceTemp">Hit F5 again, and then you’ll see the following error appear:</div>
<div class="mceTemp"> </div>
<div class="mceTemp">
<div id="attachment_248" class="wp-caption alignnone" style="width: 507px"><img class="size-full wp-image-248" title="Server error" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs16.jpg?w=497&#038;h=491" alt="Server error" width="497" height="491" /><p class="wp-caption-text">Server error</p></div>
</div>
<div class="mceTemp"> </div>
<div class="mceTemp">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.</div>
<h2 class="mceTemp">Task 3: create a view</h2>
<p class="mceTemp">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:</p>
<div id="attachment_249" class="wp-caption alignnone" style="width: 520px"><img class="size-full wp-image-249" title="Add view" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs17.jpg?w=510&#038;h=470" alt="Add view" width="510" height="470" /><p class="wp-caption-text">Add view</p></div>
<p> Then select Add View and fill in the required fields as follows: </p>
<div id="attachment_250" class="wp-caption alignnone" style="width: 511px"><img class="size-full wp-image-250" title="Add view" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs18.jpg?w=501&#038;h=538" alt="Add view" width="501" height="538" /><p class="wp-caption-text">Add view</p></div>
<p>Make sure that:</p>
<ul>
<li>The View name is called Index.</li>
<li>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.</li>
<li>Select List as the View content. This will generate code that displays a list of members.</li>
</ul>
<p>Click Add. The view Index.aspx will be generated and added to the Views/Members folder of the project:</p>
<pre><span style="color:#800080;">&lt;%@ Page Title="" Language="C#"
         MasterPageFile="~/Views/Shared/Site.Master"
         Inherits="System.Web.Mvc.ViewPage&lt;IEnumerable&lt;
                           MvcApplication1.Models.Member&gt;&gt;" %&gt;</span>
<span style="color:#800080;">&lt;asp:Content ID="Content1" ContentPlaceHolderID="TitleContent"  
             runat="server"&gt;
 Index
&lt;/asp:Content&gt;</span>
<span style="color:#800080;">&lt;asp:Content ID="Content2" ContentPlaceHolderID="MainContent"
             runat="server"&gt;</span>
<span style="color:#800080;">    &lt;h2&gt;Index&lt;/h2&gt;</span>
<span style="color:#800080;">    &lt;table&gt;
        &lt;tr&gt;
            &lt;th&gt;&lt;/th&gt;
            &lt;th&gt;
                ID
            &lt;/th&gt;
            &lt;th&gt;
                FirstName
            &lt;/th&gt;
            &lt;th&gt;
                LastName
            &lt;/th&gt;
        &lt;/tr&gt;</span>
<span style="color:#800080;">    &lt;% foreach (var item in Model) { %&gt;
   
        &lt;tr&gt;
            &lt;td&gt;
                &lt;%= Html.ActionLink("Edit", "Edit", new {
                                   /* id=item.PrimaryKey */ }) %&gt; |
                &lt;%= Html.ActionLink("Details", "Details", new {
                                   /* id=item.PrimaryKey */ })%&gt;
            &lt;/td&gt;
            &lt;td&gt;
                &lt;%= Html.Encode(item.ID) %&gt;
            &lt;/td&gt;
            &lt;td&gt;
                &lt;%= Html.Encode(item.FirstName) %&gt;
            &lt;/td&gt;
            &lt;td&gt;
                &lt;%= Html.Encode(item.LastName) %&gt;
            &lt;/td&gt;
        &lt;/tr&gt;
   
    &lt;% } %&gt;</span>
<span style="color:#800080;">    &lt;/table&gt;</span>
<span style="color:#800080;">    &lt;p&gt;
        &lt;%= Html.ActionLink("Create New", "Create") %&gt;
    &lt;/p&gt;</span>
<span style="color:#800080;">&lt;/asp:Content&gt;</span></pre>
<p>The view already contains HTML to display the list of members, and the code is very straightforward. Notice:</p>
<ul>
<li>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&lt;IEnumerable&lt;MvcApplication1.Models.Member&gt;&gt;, and therefore the Model property if of type IEnumerable&lt;MvcApplication1.Models.Member&gt; and thus we can use it in a strongly typed way.</li>
<li>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).</li>
<li>The use of Html.Encode helper method, which encodes HTML to avoid cross-site scripting.</li>
</ul>
<p> 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:</p>
<pre><span style="color:#800080;">&lt;%= Html.ActionLink("Edit", "Edit", new { id=item.ID }) %&gt; |
&lt;%= Html.ActionLink("Details", "Details", new { id=item.ID })%&gt;</span></pre>
<p>Run the web application again, change the url to <a href="http://localhost:3382/members/index">http://localhost:3382/members/index</a> and the list of members will be shown:</p>
<div id="attachment_252" class="wp-caption alignnone" style="width: 510px"><img class="size-full wp-image-252" title="My MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs19.jpg?w=500&#038;h=520" alt="My MVC application" width="500" height="520" /><p class="wp-caption-text">My MVC application</p></div>
<div class="mceTemp"> </div>
<div class="mceTemp"> Note: none of the generated links work at this point, so that’s what we’ll do next.</div>
<div class="mceTemp"> </div>
<div class="mceTemp"> Go to <a href="http://ludwigstuyck.wordpress.com/2009/06/10/asp-net-mvc-quickstart-3-implement-details-create-edit-and-delete-functionality/" target="_self">part 3</a>.</div>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ludwigstuyck.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ludwigstuyck.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ludwigstuyck.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ludwigstuyck.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ludwigstuyck.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ludwigstuyck.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ludwigstuyck.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ludwigstuyck.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ludwigstuyck.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ludwigstuyck.wordpress.com/240/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=240&subd=ludwigstuyck&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ludwigstuyck.wordpress.com/2009/06/10/asp-net-mvc-quickstart-2-implement-model-controller-and-view/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2417489f4fa437ef00401ab389ffbe9a?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">Ludwig Stuyck</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs11.jpg" medium="image">
			<media:title type="html">Add member</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs12.jpg" medium="image">
			<media:title type="html">Add controller</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs13.jpg" medium="image">
			<media:title type="html">Debugging not enabled</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs14.jpg" medium="image">
			<media:title type="html">Web page</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs15.jpg" medium="image">
			<media:title type="html">MembersController</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs16.jpg" medium="image">
			<media:title type="html">Server error</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs17.jpg" medium="image">
			<media:title type="html">Add view</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs18.jpg" medium="image">
			<media:title type="html">Add view</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs19.jpg" medium="image">
			<media:title type="html">My MVC application</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET MVC QuickStart 1: Introducing ASP.NET MVC</title>
		<link>http://ludwigstuyck.wordpress.com/2009/06/10/asp-net-mvc-quickstart-1-introducing-asp-net-mvc/</link>
		<comments>http://ludwigstuyck.wordpress.com/2009/06/10/asp-net-mvc-quickstart-1-introducing-asp-net-mvc/#comments</comments>
		<pubDate>Wed, 10 Jun 2009 12:13:32 +0000</pubDate>
		<dc:creator>Ludwig Stuyck</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://ludwigstuyck.wordpress.com/?p=224</guid>
		<description><![CDATA[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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=224&subd=ludwigstuyck&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2>Objectives</h2>
<p>In this Hands-On Lab, you will be introduced to the ASP.NET MVC framework. In particular, you will:</p>
<ul>
<li>Understand key benefits of ASP.NET MVC</li>
<li>Understand what the MVC design pattern is about</li>
<li>Create an ASP.NET MVC application</li>
<li>Understand ASP.NET MVC default routing</li>
</ul>
<h2> System requirements</h2>
<p>You must have the following items to complete this lab:</p>
<ul>
<li>Microsoft Visual Studio 2008 SP1 (professional edition)</li>
<li>Microsoft ASP.NET MVC 1.0</li>
</ul>
<h2>Prequisites</h2>
<p>You must have the following skills to understand this lab:</p>
<ul>
<li>Fundamental knowledge of software development in .NET 3.5</li>
<li>Some experience in ASP.NET web development</li>
</ul>
<h2>Task 1: Understand key benefits of ASP.NET MVC</h2>
<p>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:</p>
<ul>
<li><strong>MVC design pattern</strong>: the ASP.NET MVC framework is a modern MVC implementation</li>
<li><strong>Extensibility</strong>: 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:
<ul>
<li>Use the default implementation</li>
<li>Derive a subclass of the default implementation to tweak behavior</li>
<li>Replace a component entirely with a new implementation</li>
</ul>
</li>
<li><strong>Testability</strong>: the ASP.NET MVC framework is made to be tested using today’s testing and mocking frameworks.</li>
<li><strong>Full control</strong>: 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.</li>
<li><strong>Routing system</strong>: ASP.NET MVC works with a powerful routing system that maps search-engine friendly URL’s to actions.</li>
<li><strong>Stateless nature</strong>: embraces stateless nature of the web instead of trying to hide it and therefore avoiding complex situations.</li>
</ul>
<h2>Task 2: Understand what the MVC pattern is about</h2>
<p>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:</p>
<div id="attachment_225" class="wp-caption alignnone" style="width: 466px"><img class="size-full wp-image-225" title="MVC" src="http://ludwigstuyck.files.wordpress.com/2009/06/mvc.jpg?w=456&#038;h=420" alt="MVC" width="456" height="420" /><p class="wp-caption-text">MVC</p></div>
<p>This means that we have 3 areas of responsibility:</p>
<ul>
<li>Model: contains the business and data logic.</li>
<li>View: is responsible for presentation logic, so this is your user interface</li>
<li>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.</li>
</ul>
<p>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:</p>
<div id="attachment_227" class="wp-caption alignnone" style="width: 520px"><img class="size-full wp-image-227" title="MVC" src="http://ludwigstuyck.files.wordpress.com/2009/06/mvc2.jpg?w=510&#038;h=365" alt="MVC" width="510" height="365" /><p class="wp-caption-text">MVC</p></div>
<p>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.</p>
<h2>Task 3: Create an ASP.NET MVC application</h2>
<p>In this task you will create and configure an empty ASP.NET MVC application project using the MVC Visual Studio template.</p>
<p>Start Visual Studio 2008. Click File -&gt; New -&gt; Project, click the Web project type and select ASP.NET MVC Web Application. Give your project a name ‘MvcApplication1’ and location and click OK:</p>
<div id="attachment_228" class="wp-caption alignnone" style="width: 505px"><img class="size-full wp-image-228" title="Create new MVC project" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs1.jpg?w=495&#038;h=356" alt="Create new MVC project" width="495" height="356" /><p class="wp-caption-text">Create new MVC project</p></div>
<p>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:</p>
<div id="attachment_229" class="wp-caption alignnone" style="width: 511px"><img class="size-full wp-image-229" title="Create test project" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs2.jpg?w=501&#038;h=336" alt="Create test project" width="501" height="336" /><p class="wp-caption-text">Create test project</p></div>
<p>As a result, the solution and web project will be created, containing some default folders and files, structured to support the MVC pattern:</p>
<div id="attachment_230" class="wp-caption alignnone" style="width: 342px"><img class="size-full wp-image-230" title="Visual studio solution" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs3.jpg?w=332&#038;h=727" alt="Visual studio solution" width="332" height="727" /><p class="wp-caption-text">Visual studio solution</p></div>
<p>As you see, the most important folders are:</p>
<ul>
<li>Controllers: contains all controller classes.</li>
<li>Models: contains all models and underlying business and data logic.</li>
<li>Views: contains all views, for example .aspx or .ascx files.</li>
<li>Shared: contains all shared views, for example master pages…</li>
<li>Scripts: contains all java script files.</li>
<li>Content: contains content files, for example images, style sheets…</li>
</ul>
<p>If you run this, you will see this simple web application:</p>
<div id="attachment_232" class="wp-caption alignnone" style="width: 509px"><img class="size-full wp-image-232" title="MVC application" src="http://ludwigstuyck.files.wordpress.com/2009/06/qs4.jpg?w=499&#038;h=350" alt="MVC application" width="499" height="350" /><p class="wp-caption-text">MVC application</p></div>
<h2>Task 4: Understand ASP.NET MVC default routing</h2>
<p>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.</p>
<p>This means that a URL in the form of <a href="http://localhost">http://localhost</a>, <a href="http://localhost/home">http://localhost/home</a> or <a href="http://localhost/home/index">http://localhost/home/index</a> 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.</p>
<p>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:</p>
<pre><span style="color:#800080;">public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        return View();
    }
}</span></pre>
<p>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:</p>
<pre><span style="color:#800080;">&lt;%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
         Inherits="System.Web.Mvc.ViewPage" %&gt;
&lt;asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent"
             runat="server"&gt;
    Home Page
&lt;/asp:Content&gt;
&lt;asp:Content ID="indexContent" ContentPlaceHolderID="MainContent"
             runat="server"&gt;
    &lt;h2&gt;&lt;%= Html.Encode(ViewData["Message"]) %&gt;&lt;/h2&gt;
    &lt;p&gt;
        To learn more about ASP.NET MVC visit &lt;a
                href="</span><a href="http://asp.net/mvc"><span style="color:#800080;">http://asp.net/mvc</span></a><span style="color:#800080;">" title="ASP.NET MVC
                Website"&gt;http://asp.net/mvc&lt;/a&gt;.
    &lt;/p&gt;
&lt;/asp:Content&gt;</span></pre>
<p>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.</p>
<p><strong>Note</strong>: obviously, passing data in a loosely typed way is evil. In the next lab, we will use a strongly typed way to do this!</p>
<p>Go to <a href="http://ludwigstuyck.wordpress.com/2009/06/10/asp-net-mvc-quickstart-2-implement-model-controller-and-view/" target="_self">next part</a>.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ludwigstuyck.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ludwigstuyck.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ludwigstuyck.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ludwigstuyck.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ludwigstuyck.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ludwigstuyck.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ludwigstuyck.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ludwigstuyck.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ludwigstuyck.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ludwigstuyck.wordpress.com/224/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=224&subd=ludwigstuyck&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ludwigstuyck.wordpress.com/2009/06/10/asp-net-mvc-quickstart-1-introducing-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2417489f4fa437ef00401ab389ffbe9a?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">Ludwig Stuyck</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/mvc.jpg" medium="image">
			<media:title type="html">MVC</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/mvc2.jpg" medium="image">
			<media:title type="html">MVC</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs1.jpg" medium="image">
			<media:title type="html">Create new MVC project</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs2.jpg" medium="image">
			<media:title type="html">Create test project</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs3.jpg" medium="image">
			<media:title type="html">Visual studio solution</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/06/qs4.jpg" medium="image">
			<media:title type="html">MVC application</media:title>
		</media:content>
	</item>
		<item>
		<title>Dummy text generator</title>
		<link>http://ludwigstuyck.wordpress.com/2009/05/14/dummy-text-generator/</link>
		<comments>http://ludwigstuyck.wordpress.com/2009/05/14/dummy-text-generator/#comments</comments>
		<pubDate>Thu, 14 May 2009 11:08:26 +0000</pubDate>
		<dc:creator>Ludwig Stuyck</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://ludwigstuyck.wordpress.com/?p=221</guid>
		<description><![CDATA[Designing your web site also involves making sure that your lay-out works well in various screen resolutions and sizes, and afterwards this design has to be validated by users. To do that, you need dummy text you can use to fill up the parts of a web page. Recently I stumbled upon http://www.blindtextgenerator.com, which generates [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=221&subd=ludwigstuyck&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Designing your web site also involves making sure that your lay-out works well in various screen resolutions and sizes, and afterwards this design has to be validated by users. To do that, you need dummy text you can use to fill up the parts of a web page. Recently I stumbled upon <a href="http://www.blindtextgenerator.com" target="_blank">http://www.blindtextgenerator.com</a>, which generates this for you. If you use this, users who have to validate the design will most likely focus on the design instead on the content &#8211; because the content is meaningless. In other words: Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Understood? <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ludwigstuyck.wordpress.com/221/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ludwigstuyck.wordpress.com/221/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ludwigstuyck.wordpress.com/221/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ludwigstuyck.wordpress.com/221/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ludwigstuyck.wordpress.com/221/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ludwigstuyck.wordpress.com/221/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ludwigstuyck.wordpress.com/221/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ludwigstuyck.wordpress.com/221/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ludwigstuyck.wordpress.com/221/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ludwigstuyck.wordpress.com/221/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=221&subd=ludwigstuyck&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ludwigstuyck.wordpress.com/2009/05/14/dummy-text-generator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2417489f4fa437ef00401ab389ffbe9a?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">Ludwig Stuyck</media:title>
		</media:content>
	</item>
		<item>
		<title>I love lambda expressions (part 2)!</title>
		<link>http://ludwigstuyck.wordpress.com/2009/04/14/i-love-lambda-expressions-part-2/</link>
		<comments>http://ludwigstuyck.wordpress.com/2009/04/14/i-love-lambda-expressions-part-2/#comments</comments>
		<pubDate>Tue, 14 Apr 2009 11:35:47 +0000</pubDate>
		<dc:creator>Ludwig Stuyck</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://ludwigstuyck.wordpress.com/?p=183</guid>
		<description><![CDATA[In previous part we learned about lamda expressions, and ended up with the following example:
List&#60;int&#62; numbers = new List&#60;int&#62; { 1, 7, 16, 23, 41, 66 };
Func&#60;int, bool&#62; funcNumbersSmallerThan25 = n =&#62; n &#60; 25;
The delegate funcNumbersSmallerThan25 is compiled into executable code and can be called as follows:
List&#60;int&#62; numbersSmallerThan25 =
      numbers.Where(funcNumbersSmallerThan25).ToList();            [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=183&subd=ludwigstuyck&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In <a title="I love Lambda expressions (part 1)" href="http://ludwigstuyck.wordpress.com/2009/04/01/i-love-lambda-expressions/" target="_self">previous part </a>we learned about lamda expressions, and ended up with the following example:</p>
<pre><span style="color:#800080;">List&lt;int&gt; numbers = new List&lt;int&gt; { 1, 7, 16, 23, 41, 66 };
Func&lt;int, bool&gt; funcNumbersSmallerThan25 = n =&gt; n &lt; 25;</span></pre>
<p>The delegate funcNumbersSmallerThan25 is compiled into <strong>executable code</strong> and can be called as follows:</p>
<pre><span style="color:#800080;">List&lt;int&gt; numbersSmallerThan25 =
      </span><span style="color:#800080;">numbers.Where(funcNumbersSmallerThan25).ToList();            </span></pre>
<h1>Expression trees</h1>
<p>Now it&#8217;s time to introduce another feature called <strong>expression trees</strong>. An expression tree is a tree structure that contains lambda expressions. To demonstrate, let&#8217;s define the delegate as an expression using the following syntax:</p>
<pre><span style="color:#800080;">Expression&lt;Func&lt;int, bool&gt;&gt; exprNumbersSmallerThan25 = n =&gt; n &lt; 25;</span></pre>
<p>Now the delegate exprNumbersSmallerThan25 is no longer compiled to executable code, but instead compiled as <strong>data</strong>. In order to use it, you have to compile it to IL first:</p>
<pre><span style="color:#800080;">List&lt;int&gt; numbers = new List&lt;int&gt; { 1, 7, 16, 23, 41, 66 };
Expression&lt;Func&lt;int, bool&gt;&gt; exprNumbersSmallerThan25 = n =&gt; n &lt; 25;
var originalDelegate = exprNumbersSmallerThan25.Compile();
List&lt;int&gt; numbersSmallerThan25 = numbers.Where(originalDelegate).ToList();    </span></pre>
<p>If you call the ToString() method of the expression:</p>
<pre><span style="color:#800080;">string lambda = exprNumbersSmallerThan25.ToString();</span></pre>
<p>&#8230;you get back the lamda expression of the delegate:</p>
<div id="attachment_198" class="wp-caption alignnone" style="width: 444px"><img class="size-full wp-image-198" title="Lambda expression" src="http://ludwigstuyck.files.wordpress.com/2009/04/le.jpg?w=434&#038;h=41" alt="Lambda expression" width="434" height="41" /><p class="wp-caption-text">Lambda expression</p></div>
<p>So what we did was create a delegate exprNumbersSmallerThan25  using the lambda expression &#8216;n =&gt; n &lt; 25&#8242;, compiled it to IL code and used it. Instead of writing it using the lamba expression, you can also write it without the lamda expression:</p>
<pre><span style="color:#800080;">List&lt;int&gt; numbers = new List&lt;int&gt; { 1, 7, 16, 23, 41, 66 };
ParameterExpression n = Expression.Parameter(typeof(int), "n");
Expression body = Expression.LessThan(n, Expression.Constant(25));
Expression&lt;Func&lt;int, bool&gt;&gt; exprNumbersSmallerThan25
                       = Expression.Lambda&lt;Func&lt;int, bool&gt;&gt;(body, n);
var originalDelegate = exprNumbersSmallerThan25.Compile();
List&lt;int&gt; numbersSmallerThan25 = numbers.Where(originalDelegate).ToList();</span></pre>
<p>Actually this is exactly what internally is going on. Of course you would use lambda expressions because obviously it&#8217;s a more clear and shorter way to define an expression.</p>
<h1>Expression tree viewer</h1>
<p>To visualize expression trees, you can use the Expression Tree Visualizer tool that is part of the Visual Studio 2008 CSharp samples. To use it from Visual Studio, you have to build it first and copy the required DLL so that Visual Studio can use the visualizer:</p>
<ul>
<li>First choose Help | Samples from the Visual Studio 2008 menu, click the &#8216;local Samples folder&#8217; link and unzip the CSharpSamples/LinqSamples/ExpressionTreeVisualizer solution. </li>
<li>Build the solution and then copy the bin\debug\ExpressionTreeVisualizer.dll assembly to the &#8216;Visual Studio 2008\Visualizers&#8217; directory (to find out the directory on your system, select  Tools | Options | Projects and Solutions | General  from the Visual Studio menu)</li>
<li>Restart Visual Studio</li>
</ul>
<p>You can now test the visualizer by debugging your test project, hovering your mouse above an expression variable and clicking the magnifying glass:</p>
<div class="mceTemp">
<div id="attachment_204" class="wp-caption alignnone" style="width: 376px"><img class="size-full wp-image-204" title="Expression magnifying glass" src="http://ludwigstuyck.files.wordpress.com/2009/04/magn1.jpg?w=366&#038;h=95" alt="Expression magnifying glass" width="366" height="95" /><p class="wp-caption-text">Expression magnifying glass</p></div>
</div>
<p> Click the magnifying glass to view the expression tree:</p>
<div id="attachment_205" class="wp-caption alignnone" style="width: 402px"><img class="size-full wp-image-205" title="Expression Tree Viewer" src="http://ludwigstuyck.files.wordpress.com/2009/04/exptr.jpg?w=392&#038;h=537" alt="Expression Tree Viewer" width="392" height="537" /><p class="wp-caption-text">Expression Tree Viewer</p></div>
<h1>Why use expression trees?</h1>
<p>Expression trees provide an efficient data representation of lambda expressions (which are functions, ultimately) &#8211; so they are data structures that represent executable code. You can use them to interact with data at a low level: they can be evaluated, parsed and changed during runtime, and transformed to IL code. But why would we want to do such conversions?</p>
<p>To take an example, LINQ2SQL makes heavy use of expression trees. The following is a very simple example of a LINQ2SQL expression:</p>
<pre><span style="color:#800080;">var employees = from e in db.Employees
                where e.City == "Brussels"
                select e;</span></pre>
<p>What happens is that this expression is converted into an data structure (expression tree), and then this expression tree is analyzed by the LINQ compiler to decide the best way to convert it to SQL statements, which will be something like: </p>
<pre><span style="color:#800080;">SELECT [t0].[City], [t0].[EmployeeName]
FROM [db0].[Employees] AS [t0]
WHERE [t0].[City] = @p0</span></pre>
<p>So it&#8217;s nothing more than a transformation from expresssion -&gt; data structure -&gt; string representation. The goal of these transformation steps is to generate a data structure that is <strong>abstract</strong>, so that another process can handle it: the LINQ compiler can analyze and parse it in any way it wants (optimized for data access), or you can pass the same expression tree to some other piece of code that transforms it to something complete different, optimized for something else.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ludwigstuyck.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ludwigstuyck.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ludwigstuyck.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ludwigstuyck.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ludwigstuyck.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ludwigstuyck.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ludwigstuyck.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ludwigstuyck.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ludwigstuyck.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ludwigstuyck.wordpress.com/183/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ludwigstuyck.wordpress.com&blog=7114221&post=183&subd=ludwigstuyck&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ludwigstuyck.wordpress.com/2009/04/14/i-love-lambda-expressions-part-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2417489f4fa437ef00401ab389ffbe9a?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">Ludwig Stuyck</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/04/le.jpg" medium="image">
			<media:title type="html">Lambda expression</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/04/magn1.jpg" medium="image">
			<media:title type="html">Expression magnifying glass</media:title>
		</media:content>

		<media:content url="http://ludwigstuyck.files.wordpress.com/2009/04/exptr.jpg" medium="image">
			<media:title type="html">Expression Tree Viewer</media:title>
		</media:content>
	</item>
	</channel>
</rss>