ASP.NET MVC Framework (Part 1)

Two weeks ago I blogged about a new MVC (Model View Controller) framework for ASP.NET that we are going to be supporting as an optional feature soon.  It provides a structured model that enforces a clear separation of concerns within applications, and makes it easier to unit test your code and support a TDD workflow.  It also helps provide more control over the URLs you publish in your applications, and can optionally provide more control over the HTML that is emitted from them.

Since then I've been answering a lot of questions from people eager to learn more about it.  Given the level of interest I thought it might make sense to put together a few blog posts that describe how to use it in more detail.  This first post is one of several I'll be doing in the weeks ahead.

A Simple E-Commerce Storefront Application

I'm going to use a simple e-commerce store application to help illustrate how the ASP.NET MVC Framework works.  For today's post I'll be implementing a product listing/browsing scenario in it.

Specifically, we are going to build a store-front that enables end-users to browse a list of product categories when they visit the /Products/Categories URL on the site:

When a user clicks on a product category hyperlink on the above page, they'll navigate to a product category listing URL - /Products/List/CategoryName -  that lists the active products within the specific category:

When a user clicks an individual product, they'll navigate to a product details URL - /Products/Detail/ProductID - that displays more details about the specific product they selected:

We'll build all of the above functionality using the new ASP.NET MVC Framework.  This will enable us to maintain a "clean separation of concerns" amongst the different components of the application, and enable us to more easily integrate unit testing and test driven development.

Creating A New ASP.NET MVC Application

The ASP.NET MVC Framework includes Visual Studio Project Templates that make it easy to create a new web application with it.  Simply select the File->New Project menu item and choose the "ASP.NET MVC Web Application" template to create a new web application using it.

By default when you create a new application using this option, Visual Studio will create a new solution for you and add two projects into it.  The first project is a web project where you'll implement your application.  The second is a testing project that you can use to write unit tests against it:

You can use any unit testing framework (including NUnit, MBUnit, MSTest, XUnit, and others) with the ASP.NET MVC Framework.  VS 2008 Professional now includes built-in testing project support for MSTest (previously in VS 2005 this required a Visual Studio Team System SKU), and our default ASP.NET MVC project template automatically creates one of these projects when you use VS 2008. 

We'll also be shipping project template downloads for NUnit, MBUnit and other unit test frameworks as well, so if you prefer to use those instead you'll also have an easy one click way to create your application and have a test project immediately ready to use with it.

Understanding the Folder Structure of a Project

The default directory structure of an ASP.NET MVC Application has 3 top-level directories:

  • /Controllers
  • /Models
  • /Views

As you can probably guess, we recommend putting your Controller classes underneath the /Controllers directory, your data model classes underneath your /Models directory, and your view templates underneath your /Views directory. 

While the ASP.NET MVC framework doesn't force you to always use this structure, the default project templates use this pattern and we recommend it as an easy way to structure your application.  Unless you have a good reason to use an alternative file layout, I'd recommend using this default pattern.

Mapping URLs to Controller Classes

In most web frameworks (ASP, PHP, JSP, ASP.NET WebForms, etc), incoming URLs typically map to template files stored on disk.  For example, a "/Products.aspx" or "/Products.php" URL typically has an underlying Products.aspx or Products.php template file on disk that handles processing it.  When a http request for a web application comes into the web server, the web framework runs code specified by the template file on disk, and this code then owns handling the processing of the request.  Often this code uses the HTML markup within the Products.aspx or Products.php file to help with generating the response sent back to the client.

MVC frameworks typically map URLs to server code in a different way.  Instead of mapping URLs to template files on disk, they instead map URLs directly to classes.  These classes are called "Controllers" and they own processing incoming requests, handling user input and interactions, and executing appropriate application and data logic based on them.  A Controller class will then typically call a separate "View" component that owns generating the actual HTML output for the request.

The ASP.NET MVC Framework includes a very powerful URL mapping engine that provides a lot of flexibility in how you map URLs to Controller classes.  You can use it to easily setup routing rules that ASP.NET will then use to evaluate incoming URLs and pick a Controller to execute.  You can also then have the routing engine automatically parse out variables that you define within the URL and have ASP.NET automatically pass these to your Controller as parameter arguments.  I'll be covering more advanced scenarios involving the URL routing engine in a future blog post in this series.

Default ASP.NET MVC URL Routing to Controller Classes

By default ASP.NET MVC projects have a preconfigured set of URL routing rules that enable you to easily get started on an application without needing to explicitly configure anything.  Instead you can start coding using a default set of name-based URL mapping conventions that are declared within the ASP.NET Application class of the Global.asax file created by the new ASP.NET MVC project template in Visual Studio. 

The default naming convention is to map the leading URL path of an incoming HTTP request (for example: /Products/) to a class whose name follows the pattern UrlPathController (for example: by default a URL leading with /Products/ would map to a class named ProductsController).

To build our e-commerce product browsing functionality, we'll add a new "ProductsController" class to our project (you can use the "Add New Item" menu in Visual Studio to easily create a Controller class from a template):

Our ProductsController class will derive from the System.Web.MVC.Controller base class.  Deriving from this base class isn't required - but it contains some useful helper methods and functionality that we'll want to take advantage of later:

Once we define this ProductsController class within our project, the ASP.NET MVC framework will by default use it to process all incoming application URLs that start under the "/Products/" URL namespace.  This means it will be automatically called to process the "/Products/Categories", "/Products/List/Beverages", and "/Products/Detail/3" URLs that we are going to want to enable within our store-front application.

In a future blog post we'll also add a ShoppingCartController (to enable end users to manage their shopping carts) and an AccountController (to enable end users to create new membership accounts on the site and login/logout of it).  Once we add these two new controller classes to our project, URLs that start with /ShoppingCart/ and /Account/ will automatically be routed to them for processing.

Note: The ASP.NET MVC framework does not require that you always use this naming convention pattern.  The only reason our application uses this by default is because there is a mapping rule that configures this that was automatically added to our ASP.NET Application Class when we created the new ASP.NET MVC Project using Visual Studio.  If you don't like this rule, or want to customize it to use a different URL mapping pattern, just go into the ASP.NET Application Class (in Global.asax) and change it. I'll cover how to-do this in a future blog post (when I'll also show some of the cool scenarios the URL routing engine enables).

Understanding Controller Action Methods

Now that we have a created a ProductsController class in our project we can start adding logic to handle the processing of incoming "/Products/" URLs to the application.

When defining our e-commerce storefront use cases at the beginning of this blog post, I said we were going to implement three scenarios on the site: 1) Browsing all of the Product Categories, 2) Listing Products within a specific Category, and 3) Showing Details about a Specific Product.  We are going to use the following SEO-friendly URLs to handle each of these scenarios:

URL Format Behavior URL Example
/Products/Categories Browse all Product Categories /Products/Categories
/Products/List/Category List Products within a Category /Products/List/Beverages
/Products/Detail/ProductID Show Details about a Specific Product /Products/Detail/34

There are a couple of ways we could write code within our ProductsController class to process these three types of incoming URLs.  One way would be to override the "Execute" method on the Controller base class and write our own manual if/else/switching logic to look at the incoming URL being requested and then execute the appropriate logic to process it.

A much easier approach, though, is to use a built-in feature of the MVC framework that enables us to define "action methods" on our controller, and then have the Controller base class automatically invoke the appropriate action method to execute based on the URL routing rules in use for our application.

For example, we could add the below three controller action methods to our ProductsController class to handle our three e-commerce URL scenarios above:

The URL routing rules that are configured by default when a new project is created treat the URL sub-path that follows the controller name as the action name of the request.  So if we receive a URL request of /Products/Categories, the routing rule will treat "Categories" as the name of the action, and the Categories() method will be invoked to process the request.  If we receive a URL request of /Products/Detail/5, the routing rule will treat "Detail" as the name of the action, and the Detail() method will be invoked to process the request, etc. 

Note: The ASP.NET MVC framework does not require that you always use this action naming convention pattern.   If you want to use a different URL mapping pattern, just go into the ASP.NET Application Class (in Global.asax) and change it.

Mapping URL Parameters to Controller Action Methods

There are several ways to access URL parameter values within the action methods of Controller classes.

The Controller base class exposes a set of Request and Response objects that can be used.  These objects have the exact same API structure as the HttpRequest/HttpResponse objects that you are already familiar with in ASP.NET.  The one important difference is that these objects are now interface based instead of sealed classes (specifically: the MVC framework ships with new System.Web.IHttpRequest and System.Web.IHttpResponse interfaces).  The benefit of having these be interfaces is that it is now easy to mock them - which enables easy unit testing of controller classes.  I'll cover this in more depth in a future blog post. 

Below is an example of how we could use the Request API to manually retrieve an ID querystring value from within our Detail action method in the ProductsController class:

The ASP.NET MVC framework also supports automatically mapping incoming URL parameter values as parameter arguments to action methods.  By default, if you have a parameter argument on your action method, the MVC framework will look at the incoming request data to see if there is a corresponding HTTP request value with the same name.  If there is, it will automatically pass it in as a parameter to your action method.

For example, we could re-write our Detail action method to take advantage of this support and make it cleaner like below:

In addition to mapping argument values from the querystring/form collection of a request, the ASP.NET MVC framework also allows you to use the MVC URL route mapping infrastructure to embed parameter values within the core URL itself (for example: instead of /Products/Detail?id=3 you could instead use /Products/Detail/3). 

The default route mapping rule declared when you create a new MVC project is one with the format: "/[controller]/[action]/[id]".  What this means is that if there is any URL sub-path after the controller and action names in the URL, it will by default be treated as a parameter named "id" - and which can be automatically passed into our controller action method as a method argument.

This means that we can now use our Detail method to also handle taking the ID argument from the URL path (e.g: /Products/Detail/3):

I can use a similar approach for the List action so that we can pass in the category name as part of the URL (for example: /Products/List/Beverages).  In the interest of making the code more readable, I made one tweak to the routing rules so that instead of having the argument name be called "id" it will be called "category" for this action.

Below is a version of our ProductsController class that now has full URL routing and parameter mapping support implemented:

Note above how the List action takes the category parameter as part of the URL, and then an optional page index parameter as a querystring (we'll be implementing server-side paging and using that value to indicate which page of category data to display with the request). 

Optional parameters in our MVC framework are handled using nullable type arguments on Controller Action methods.  Because the page parameter on our List action is a nullable int (that is what "int?" means syntactically), the MVC framework will either pass in a value if it is present in the URL - or pass in null if not.  Check out my previous post on the ?? null coalescing operator to learn a useful tip/trick on how to work with nullable types that are passed as arguments like this.

Building our Data Model Objects

We now have a ProductsController class and three action methods on it ready to process incoming web requests.  Our next step will be to build some classes that will help us work with our database to retrieve the appropriate data needed to handle these web requests.

In an MVC world "models" are the components of an application that are responsible for maintaining state.  With web applications this state is typically persisted inside a database (for example: we might have a Product object that is used to represent product data from the Products table inside our SQL database).

The ASP.NET MVC Framework enables you to use any data access pattern or framework you want in order to retrieve and manage your models.  If you want to use ADO.NET DataSets/DataReaders (or abstractions built on top of them) you can.  If you prefer to use an object relational mapper (ORM) like NHibernate, LLBLGen, WilsonORMapper, LINQ to SQL/LINQ to Entities you can absolutely use those as well.

For our e-commerce sample application I'm going to use the built-in LINQ to SQL ORM shipped in .NET 3.5 and VS 2008.  You can learn more about LINQ to SQL from my ongoing blog tutorial series that covers it (in particular make sure to check out my Part1, Part2, Part3 and Part4 posts). 

I'll start by right-clicking on the "Models" sub-directory of our MVC web project inside VS and choose the "Add New Item" option to add a LINQ to SQL model.  Within the LINQ to SQL ORM designer I'll define three data model classes that map to the Categories, Products, and Suppliers table inside the SQL Server Northwind sample database (read Part 2 of my LINQ to SQL series to learn how to-do this):

Once we've defined our LINQ to SQL data model classes, I'll then add a new NorthwindDataContext partial class to our Models directory as well:

Within this class I'll define a few helper methods that encapsulate some LINQ expressions that we can use to retrieve the unique Category objects from our database, retrieve all Product objects within a specific category in our database, as well as retrieve an individual Product object based on a supplied ProductID:

These helper methods will make it easy for us to cleanly retrieve the data model objects needed from our ProductsController class (without having to write the LINQ expressions within the Controller class itself):

We now have all of the data code/objects we need to finish implementing our ProductsController functionality. 

Finishing the Implementation of our ProductsController Class

Controllers in a MVC based application are responsible for processing incoming requests, handling user input and interactions, and executing appropriate application logic based on them (retrieving and updating model data stored in a database, etc).

Controllers typically do not generate the specific HTML response for a request.  The task of generating an HTML response is instead owned by "View" components within the application - which are implemented as separate classes/templates from Controllers.  Views are intended to be focused entirely on encapsulating presentation logic, and should not contain any application logic or database retrieval code (instead all app logic should be handled by the Controller).

In a typical MVC web workflow, Controller action methods will handle the incoming web request, use the incoming parameter values to execute appropriate application logic code, retrieve or update data model objects from a database, and then select a "View" to use to render an appropriate UI response back to a browser.  As part of picking the appropriate View to render, the Controller will explicitly pass in (as arguments) all of the data and variables required by the "View" in order to for it to render the appropriate response:

You might be wondering - what is the benefit of separating the Controller and the View like this?  Why not just put them in the same class?  The primary motivation in partitioning the application like this is to help enforce the separation of your application/data logic from your UI generation code.  This makes it much easier to unit test your application/data logic in isolation from your UI rendering logic.  It can also help make your application more maintainable over time - since it makes it harder for you to accidentally add application/data logic in your view templates.

When implementing the three controller action methods of our ProductsController class, we'll use the incoming URL parameter values to retrieve the appropriate model objects from our database, and then pick a "View" component to use to render an appropriate HTML response.  We'll use one of the RenderView() methods on the Controller base class to specify the View we want to use, as well as explicitly pass in the specific data that we want the View to use to render its response.

Below is the final result of our ProductsController implementation:

Notice that the number of lines of code in our action methods above is pretty small (two lines each).  This is partly because the URL parameter parsing logic is handled entirely for us by the MVC framework (saving us from having to write a lot of this code).  This is also partly because the product browsing scenario is fairly simple from a business logic perspective (the action methods are all read-only display scenarios). 

In general, though, you'll often find that you'll have what are sometimes called "skinny controllers" - meaning controller methods full of relatively terse action methods (less than 10 lines of code).  This is often a good sign that you have cleanly encapsulated your data logic and factored your controller logic well.

Unit Testing our ProductsController

You might be surprised that the next step we are going to work on is to test our application logic and functionality.  You might ask - how is that even possible?  We haven't implemented our Views, and our application currently doesn't render a single tag of HTML.  Well, part of what makes an MVC approach attractive is that we can unit test the Controller and Model logic of applications completely independently of the View/Html generation logic.  As you'll see below we can even unit test these before we create our Views.

To unit test the ProductsController class that we've been working on, we'll add a ProductsControllerTest class into the Test Project that was added to our solution by default when we created our ASP.NET MVC Application using Visual Studio:

We'll then define a simple unit test that tests the Detail action of our ProductsController:

The ASP.NET MVC framework has been designed specifically to enable easy unit testing.  All core APIs and contracts within the framework are interfaces, and extensibility points are provided to enable easy injection and customization of objects (including the ability to use IOC containers like Windsor, StructureMap, Spring.NET, and ObjectBuilder).  Developers will be able to use built-in mock classes, or use any .NET type-mocking framework to simulate their own test versions of MVC related objects.

In the unit test above, you can see an example of how we are injecting a dummy "ViewFactory" implementation on our ProductsController class before calling the Detail() action method.  By doing this we are overriding the default ViewFactory that would otherwise handle creating and rendering our View.  We can use this test ViewFactory implementation to isolate the testing of just our ProductController's Detail action behavior (and not have to invoke the actual View to-do this).  Notice how we can then use the three Assert statements after the Detail() action method is called to verify that the correct behavior occurred within it (specifically that the action retrieved the correct Product object and then passed it to the appropriate View).

Because we can mock and simulate any object in the MVC framework (including IHttpRequest and IHttpResponse objects), you do not have to run unit tests in the context of an actual web-server.  Instead, we can create our ProductsController within a normal class library and test it directly.  This can significantly speed up the execution of unit tests, as well as simplify the configuration and running of them.

If we use the Visual Studio 2008 IDE, we can also easily track the success/failure of our test runs (this functionality is now built-into VS 2008 Professional):

I think you'll find that the ASP.NET MVC Framework makes writing tests easy, and enables a nice TDD workflow.

Rendering UI with Views

We've finished implementing and testing the application + data logic for the product browsing section of our e-commerce application.  Now we need to implement the HTML UI for it. 

We'll do this by implementing "Views" that render the appropriate UI using the view-related data objects that our ProductsController action method provided when calling the RenderView() method:

In the code example above the RenderView method's "Categories" parameter is indicating the name of the view we want to render, and the second parameter is a list of category objects that we want to pass to the view and have it use as data to generate the appropriate HTML UI for.

The ASP.NET MVC Framework supports the ability to use any templating engine to help with generating UI (including existing templating engines like NVelocity, Brail - as well as new ones you write yourself).  By default the ASP.NET MVC Framework uses the existing ASP.NET Page (.aspx), Master Page (.master), and UserControl (.ascx) support already within ASP.NET. 

We'll be using the built-in ASP.NET view engine to implement our E-commerce Application UI.

Defining a Site.Master File

Because we are going to be building many pages for our site, we'll start our UI work by first defining a master page that we can use to encapsulate the common HTML layout/chrome across the site. We'll do this in a file called "Site.Master" that we'll create under the \Views\Shared directory of our project:

We can reference an external CSS stylesheet to encapsulate all styles for the site, and then use the master page to define the overall layout of the site, as well as identify content placeholder regions where we'll want pages to be able to fill in page specific content.  We can optionally use all of the cool new VS 2008 designer features when doing this (including the HTML split-view designer, CSS Authoring, and Nested Master Pages support).

Understanding the /Views Directory Structure

By default when you create a new ASP.NET MVC Project using Visual Studio, it will create a "Shared" sub-directory underneath the "Views" directory root.  This is the recommended place to store Master Pages, User Controls, and Views that we want to share across multiple Controllers within the application.

When building views that are specific to an individual controller, the default ASP.NET MVC convention is to store them in sub-directories under the \Views root.  By default the name of a sub-directory should correspond to the Controller name.  For example, because the Controller class we have been building is called "ProductsController", we will by default store the Views specific to it within the \Views\Products sub-directory:

When we call the RenderView(string viewName) method within a specific Controller, the MVC framework will automatically first look for a corresponding .aspx or .ascx view template underneath the \Views\ControllerName directory, and then if it can't find an appropriate view template there it will check the \Views\Shared directory for one:

Creating a Categories View

We can create the "Categories" View for our ProductsController within Visual Studio by using the "Add New Item" menu option on the Products directory and selecting the "MVC View Page" item template.  This will create a new .aspx page that we can optionally associate with our Site.Master master page to pick up the overall look and feel of the site (and just like with master pages you get full WYSIWYG designer support):

When building applications using an MVC pattern, you want to keep your View code as simple as possible, and make sure that the View code is purely about rendering UI.  Application and data retrieval logic should only be written inside Controller classes.  Controller classes can then choose to pass on the necessary data objects needed to render a view when they call their RenderView method.  For example, below in the Categories action method of our ProductsController class we are passing a List collection of Category objects to the Categories view:

MVC View Pages by default derive from the System.Web.Mvc.ViewPage base class, which provides a number of MVC specific helper methods and properties that we can use in constructing our UI.  One of these ViewPage properties is named "ViewData", and it provides access to the view-specific data objects that the Controller passed as arguments to the RenderView() method.

From within your View you can access the "ViewData" in either a late-bound or strongly-typed way.  If your View derives from ViewPage, the ViewData property will be typed as a late-bound dictionary.  If your View derives from the generics based ViewPage<T> - where T indicates the data object type of the ViewData the Controller is passing to the View - then the ViewData property will be strongly typed to match the same type that your Controller passed in.

For example, my Categories View code-behind class below is deriving from ViewPage<T> - where I am indicating that T is a List of Category objects:

This means that I get full type-safety, intellisense, and compile-time checking within my View code when working against the ProductsController.Categories() supplied List<Category> ViewData:

Rendering our Categories View:

If you remember from the screenshots at the very beginning of this post, we want to display a list of the product categories within our Categories view:

I can write this HTML UI generation code in one of two ways within my Categories View implementation: 1) Using Inline Code within the .aspx file, or 2) Using Server Controls within the .aspx file and Databinding from my Code Behind

Rendering Approach 1: Using Inline Code

ASP.NET Pages, User Controls and Master Pages today support <% %> and <%= %> syntax to embed rendering code within html markup.  We could use this technique within our Categories View to easily write a foreach loop that generates a bulleted HTML category list:

VS 2008 provides full code intellisense within the source editor for both VB and C#.  This means we'll get intellisense against our Category model objects passed to the View:

VS 2008 also provides full debugger support for inline code as well (allowing us to set breakpoints and dynamically inspect anything in the View with the debugger):

Rendering Approach 2: Using Server Side Controls

ASP.NET Pages, User Controls and Master Pages also support the ability to use declarative server controls to encapsulate HTML UI generation.  Instead of using inline code like above, we could use the new <asp:listview> control in .NET 3.5 to generate our bulleted list UI instead:

Notice above how the ListView control encapsulates both rendering a list of values, as well as handles the scenario where no items are in the list (the <EmptyDataTemplate> saves us from having to write an if/else statement in the markup).  We could then databind our list of category objects to the listview control using code-behind code like below:

Important: In a MVC world we only want to put rendering logic in our View's code-behind class (and not any application or data logic).  Notice above how the only logic we have is to assign the strongly typed ViewData collection of Category objects to the ListView control.   Our ProductsController Controller class is the one that actually retrieves the list of Categories from the database - not the View. 

This ListView server-control version of our View template will then generate the exact same HTML as our in-line code version.  Because we don't have a <form runat="server"> control on the page, no viewstate, ID values or other markup will be emitted.  Only pure CSS friendly HTML:

 

Html.ActionLink Method

One of the things you might have noticed in both the inline-code and the server-control versions of the View code snippets above are calls to an Html.ActionLink method:

The Html object is a helper property on the ViewPage base class, and the ActionLink method is a helper on it that makes it easy to dynamically generate HTML hyperlinks that link back to action methods on Controllers. If you look at the HTML output picture in the section above, you can see some example HTML output generated by this method:

<a href="/Products/List/Beverages">Beverages</a>

The signature of the Html.ActionLink helper method I am using looks like this:

string ActionLink(string text, object values);

The first argument represents the inner content of the hyperlink to render (for example: <a>text goes here</a>).  The second argument is an anonymous object that represents a sequence of values to use to help generate the actual URL (you can think of this as a cleaner way to generate dictionaries).  I will go into more detail on how exactly this works in a future blog post that covers the URL routing engine.  The short summary, though, is that you can use the URL routing system both to process incoming URLs, as well as to generate URLs that you can emit in outgoing HTML.  If we have a routing rule like this:

/<controller>/<action>/<category>

And then write this code within a ProductController's Category View:

<%= Html.ActionLink("Click Me to See Beverages", new { action="List", category="Beverages" } %>

The ActionLink method will use the URL mapping rules of your application to swap in your parameters and generate this output:

<a href="/Products/List/Beverages">Click Me to See Beverages</a>

This makes it easy within your application to generate URLs and AJAX callbacks to your Controllers.  It also means you can update your URL routing rules in one place and have the code throughout your application automatically pick up the changes for both incoming URL processing and outgoing URL generation.

Important Note: To help enforce testability, the MVC framework today does not support postback events directly to server controls within your Views.  Instead, ASP.NET MVC applications generate hyperlink and AJAX callbacks to Controller actions - and then use Views (and any server controls within them) solely to render output.  This helps ensure that your View logic stays minimal and solely focused on rendering, and that you can easily unit test your Controller classes and verify all Application and Data Logic behavior independent of your Views.  I'll blog more about this in the future.

Summary

This first blog post is a pretty long one, but hopefully helps provide a reasonably broad look at how all the different components of the new ASP.NET MVC Framework fit together, and how you can build a common real world scenario with it.  The first public preview of the ASP.NET MVC bits will be available in a few weeks, and you'll be able to use them to do all of the steps I outlined above.

While many of the concepts inherent to MVC (in particular the idea of separation of concerns) are probably new to a lot of people reading this, hopefully this blog post has also show how the ASP.NET MVC implementation we've been working on fits pretty cleanly into the existing ASP.NET, .NET, and Visual Studio feature-set.  You can use .ASPX, .ASCX and .MASTER files and ASP.NET AJAX to create your ASP.NET MVC Views.  Non-UI features in ASP.NET today like Forms Authentication, Windows Authentication, Membership, Roles, Url Authorization, Caching, Session State, Profiles, Health Monitoring, Configuration, Compilation, Localization, and HttpModules/HttpHandlers all fully support the MVC model.

If you don't like the MVC model or don't find it natural to your style of development, you definitely don't have to use it.  It is a totally optional offering - and does not replace the existing WebForms Page Controller model.  Both WebForms and MVC will be fully supported and enhanced going forward.  You can even build a single application and have parts of it written using WebForms and parts written using an MVC approach if you want.

If you do like what you've seen from the above MVC post (or are intrigued and want to learn more), keep an eye on my blog over the weeks ahead.  I'll be covering more MVC concepts and use them to build out our e-commerce application to show more features of it.

Hope this helps,

Scott

258 Comments

  • I'm looking forward to the upcoming articles!
    Thank you :-)

  • How will Ajax and data entry enter into this model (as Ajax has taken a great hold on data entry nowadays)? That is, those that require postbacks, not to mention all the third part libraries that currently use the postback methods. Is there any way to use them under this model?

    Thanks. Saw you video a couple weeks ago abou MVC, was pretty good!

  • Yet again -another awesome post.

  • Hi Scott,

    This is amazing, would it be possible for you to demonstrate this part in a screencast or maybe next part?

    Or something like create a blog in 15 minutes?

  • Hey G! It was what i was waiting to see ! I can't wait to mess up with it.
    I use CastleProject and I didn't like using Ajax so I wonder how to use ASP.NET Ajax feauters ? I was trying to create a helper class to use ASP.NET ajax in castleProject. Will you do it like HtmlHelper ?

    Thank you !
    Regards.

  • Hello Scott,

    Have you and the team any plans of including something like scaffolding? where by pointing at a database table clean basic code would be generated for listing,viewing,adding,editing,deleting etc.?

    This would be a great kick start for beginners like me.

  • Wow, now that is a posting! And this is only part 1? ;-)

  • Hi Scott,

    Thanks for the post. Since it is early days for this project and SL 1.1 is still in Alpha, are there any plans to allow us to use this MVC model for SL applications?

    Thanks,

    John

  • Same here, I love the "Part 1" part of the title (although I'll also be looking for the words "release date" ;-))

  • Really excited as to where this is heading for ASP.NET

  • Scott,

    This is a fantastic addition to the ASP.NET arena. I am looking forward to the future blogs as well as implementing the MVC methodology in production ASP.NET apps once VS2008 is released.

  • Hi Scott,

    Thanks for your insightfull posts. I want to follow this demo on my own computer, but I wonder where I can this ASP.NET MVC project template.

    keep up the good work,

    Anthony

  • I like the level of abstraction and seperation, which is something I've always done in the past by having 3 projects inside Visual Studio. One for data access, one for business logic and a website project for UI.

    What MVC provides for me, seems to be a cleaner way of calling corresponding methods inside of those layers, and taking care of all the URL rewriting, parameter 'loading' and so forth.

    But the fact that I sometimes need to use the same business logic and data access from other apps that websites, makes me think that I would not benefit that much from the MVC. I would end up with a lot of skinny-methods, but on the other hand it would be easy to use the same website with another application logic without rewriting the aspx codebehind files.

    Looking forward to play with it myself, and see how it all fits in...

  • Wow! Scott, thanks for the long post.

    Cant wait for more info on these MVC concepts.

    Cheers

  • Can I only pass one object to the View via RenderView or is there a mechanism to pass multiple objects/value types? I'm guessing the convention is to lead me towards an 'interface per view' contract that specifies all data that will be made available?

  • Cool intro Scott. I cannot wait to get first-hand experience

  • Where or when can I download the CTP?

  • Scott - This looks very promising indeed, and for the first time in a while, makes the Microsoft ASP.NET story much more appealing to lots of us. Good job in getting it back on the rails...

  • It's great!
    And I wonder if the source code of this sample application is available.
    Thanks a lot.

  • I love this guy!!!
    Waiting for the next episode, thanks Scott

  • Awesome article! Thank you, Scott. I've kicked you :)

  • So cool !!!! I have learned so much from your blog. Thank you so much and keep posting plz.

  • This all looks really cool!

    I have one question: What was the reasoning behind having Html.ActionLink as opposed to a more standard ASP.NET type approach of an control? Using methods that generate strings of HTML seems like a step back from the server control architecture that makes ASP.NET so cool in the first place.

    Of course it would be trivial to write an ActionLink server control that calls Html.ActionLink in its Render method. Have you considered including something like this?

  • Hey Scott,

    Great article, can't wait to try it out. On a seperate note, any hint on when VS2008 will rtm?

    Jonathan

  • It is really similar to web client software factory WCSF, however from my experience with WCSF it turns out to be more overhead, may be because of the workflow, I hope this one is better and really makes our life easier

  • Fantastic post! So excited about getting my hands on the framework!

  • While you are talking about mocking objects for TDD, would you consider including how to mock out any orm being used. Thanks

  • Can´t wait until the bits come out. Thanks for this overview Scott.

  • Hi Scott;
    I'm sure you guys have spent a lot of work into this technology and it will take a good amount of time for us to become good at. My question is, do you think this kind of technology will make it's way to the Silverlight platform, so we both can benefit from the invested time and energy?
    Thanks!
    ..Ben

  • Since it adds a testing project, does this require Team System?

  • Awesome, thanks for this post! I was really looking forward to some more information on this project. To me, besides LINQ, it's the one thing I'm looking forward to most.

    I have some questions that I hope you can answer:

    1. Only Web Application model will be supported, not Web Site?
    2. Is it also possible to have this URL mapped: /Products/Beverages/3 instead of /Products/Beverages?page=3 or does it _need_ the parameter name?

    Also, some ideas and general remarks:

    1. I'd love to see more helper methods for use in the views, I like how Ruby on Rails has many shortcuts for creating forms and formfields etc.
    2. Migrations! Not a part of MVC but from my experience with Ruby on Rails I would love to see support for this somewhere, anywhere! It would fit perfectly with the more agile way of developing that is possible with ASP.NET MVC.

    Again, thanks for this post, I can't wait for the first release!

  • Feature request - please please include a comparable feature to the Castle MonoRail SmartDispatcherController that automatically binds to Post variables submitted by form elements such as and . Or is this sort of functionality what you see the current frameworks providing on top of Microsoft MVC?

  • Brillian article - it makes it very simple to understand!

    Well done for all the hard work on the MVC implementation - looks like it is paying off! I'm first in line to get a copy of VS2008 and end my love/hate relationship with PageControllers :)

    Thanks Scott!

  • What about Web Parts, are they supported ? Is it possible to develop Web Parts by using MVC ?

  • Hi Scott,

    Where I can download source code for this post?

    Thanks,
    Gary

  • Thanks Scott. I'm really excited to see this coming to ASP.NET.

    What would happen in your products detail example when the user changes the product id in the url to something that isn't an integer such as "/Products/Detail/ABC"? Will an exception be thrown since the ProductsController.Detail method is expecting an int?

  • Is it possible to test drive view in isolation, i.e. render it without full ASP.NET pipeline? It's necessary thing when using TDD for web development.

  • Awesome! Can't wait for the CTP!

    How do you put the List page parameter into the core URL like you did with the category string? I guess I'm asking where you can define more comprehensive routing rules.

    Can you map a nullable type to a url segment? like /Products/List/CatName/23 and can you leave it blank like this /Products/List/CatName/?





  • Hey Now Scott,
    Great content.
    Thanks for the info,
    Catto

  • I have been waiting for this for a long time. This will change the way we do ASP.Neting currently and will force others (adopters of MVC) to learn Generics for sure. All goodies! :)

  • I'm also very keen to get my hands on the CTP. Scott, you mention, using Inversion of Control containers with the MVC framework. I'd be very interested in seeing a blog post on this subject. Also, will there be a sample application (with tests and IoC) available alonside the CTP?

  • Very cool! One thing I'd like to see guidance on is developing MVC apps with multiple UIs. You say here that it's best to put your models and controllers in the web app, but say we want a Winforms, WPF, Silverlight, and Web UI all doing similar things. Or a Mobile Web UI and Desktop Web UI... Would these still each need their own Models and Controllers, or does it make sense to have one library that they all share? If so, how is that supported? I'm still new to MVC, so if I'm missing something conceptually here, tell me!

  • This is great stuff. I can't wait to get my hands on it.

  • Excellent Article - I'm really looking forward to this technology. There has always been a disconnect between true enterprise development standards, and the typical website "page" model. This exposes control over the process, and the end users experience. Wonderful stuff!

  • Thank you for what I suspect will be among the most interesting .NET technologies to have been released in the last 2 years.

  • Great Post!

    How would you go about populating several data driven dropdown lists as well as loading the page content without putting data access logic in the view?

  • I really appreciate this material. Do you support the MVC pattern over the MVP pattern? Or are there just better scenarios for using each?

  • Right time, right place :-).
    Looking forward to model, view and control.
    cheers, idaniel

  • Now THIS is the post I have been waiting for. Very nicely written, keep up the great work Scott!

  • Great explanation. Thanks Scott

  • Thanks for this excellent writeup. You've done a good job of clarifying some important points about the new pattern. Anyone familiar with other popular MVC frameworks for .net can see the comparison quite cleanly here.

  • Great Post. Could I do this with the Front Controller pattern as well? (Without the mvc framework)

  • This looks spectacular! Can you tell us when to expect a (beta) release? Can't wait to try it out myself! :-)

  • Naming a framework after a desugn pattern really drives the novices like me to panic and delays experimenting with it. Till now i was learning design patterns transparently using the .net framework. Is there any plan to change the asp.net mvc framework name to something tasty?

  • This writeup is masterful! Thanks for the monumental effort; it's extremely helpful!

  • Great, I saw your earlier material about MVC but somehow could not find that when it is going to be available. Now it is clear that it is part of VS 2008

  • a very great article!
    waiting to download the first CTP release :)

  • This looks very promising. I will definitely try this out. Thanks!

  • So the controller deals with the incomming request. If I understand correclty, if I need to add a new "page" to my website I need to modify my controller and recompile the application?

    Whould I end up with a single controller entry

  • Awesome. Can't wait for the bits. You talked about using an ASP.Net ListView control that is not inside a tag. What if I want to use controls that must be inside such a tag?
    It doesn't look like this will work with the ASP.Net AJAX UpdatePanel control. Will you be enhancing ASP.Net AJAX so that it integrates with the new MVC stuff? I can see wanting to hit a url like /Products/Detail/3 and it return just the markup for the detail of that product (or maybe a JSON serialized Product object). Will this be easy?

  • Hi Scott,
    using server side controls I see a problem on handling the control naming convention with MVC framework (actually also with 'normal' asp.net coding).

    If I have this code


    in the calling page, I have to handle a name like
    ctl00$ContentPlaceHolder1$txtMyMessage

    How is it handled this situation in MVC?

    Sorry if you planned to speculate on this in the following posts ;P

    Great post!

    Ciao
    Carlo

  • Awesome! I con't wait to start playing with this. One thing I'd like to see in a future post is, how are user controls that need a controller going to work? (For example, a data driven hierarchical menu that might live in the left pane of a web site.)

  • Very nice to see this, can't wait to get the bits also!

  • The ASP.NET MVC Framework is looking good, but I'm unsure how this will fit into custom MOSS 2007 development. Are you taking into consideration that we would like to use this framework for custom development ontop of MOSS? MOSS includes it's own URL rewriting/handling, I expect that to create problems for this new framework.

    Are you considering support and implementation on MOSS - this is important for a lot of companies as more and more solutions are being development on that platform, and not from a scratch with an empty ASP.NET solution.

  • This looks really great and I can't wait to start using it. I had a few questions / comments on parts of the design.
    1. Wouldn't it make more sense to separate the models and controllers into their own class libraries?
    2. Will all the MVC features be available in VS 2005?
    3. How come URL rewriting is managed in the Global.asax? Can this be managed from within a IHttpModule?
    4. How about making the action to execute a property of the [ControllerAction] attribute so it doesn't depend on the method name? For example, [ControllerAction(Action="Detail")]

    Looks great!

  • How is input validation going to work? Is there a place in the controller where you can register validation errors and then access them from the view similar to the ViewData property?

  • thanks a lot

  • let me quote charles: outstanding! ;)

  • Great article. can't wait to use the MVC framework.

  • It would be great to see an example of a round trip from a read only list view page, to a form using whatever the framework uses for databinding, and back to the list view.

  • Great article! I have 2 quick questions, one is that when you built the view, you have an approach Using Inline Code which got intellisense, do you recommend using this approach? Compare this to using the server control in this particular snippet of example, it looks shorter and cleaner than server control. Second question is in which one of your LINQ tutorial did you discuss caching? Basically, when user browse your catalog the first time the Model got the data from DB and should cache it for a while on server, right?

  • I like where this is heading... But how will handheld devices handle ajax?
    MVC should have been released years ago, this is how asp.net should have worked from the begining!

  • Excellent article! Where are the bits? Can't wait to start playing with it.

  • Thanks for detail MVC overview.

    I have questions about state management. where we suppose to put state management logic using ViewState or Session. Will it be going in aspx page(view) or in Controller? if we use it in View, we are trying to control something and according to MVC pattern it should be in controller. If we put it in Controller, our view and controller both become tightly coupled with each other, which creates some contradiction.

  • Good article.
    but..
    Where should we put state management logic (ViewState or Session)? in controller or in view. if we put in view, we are meshing up with UI rules. if we put it in controllers, view and controllers become tightly coupled which would create contradiction. Should we go for separate State Management engine using ASP.NET state management technique and use it with controller or view?

  • Good article.
    but..
    Where should we put state management logic (ViewState or Session)? in controller or in view. if we put in view, we are meshing up with UI rules. if we put it in controllers, view and controllers become tightly coupled which would create contradiction. Should we go for separate State Management engine using ASP.NET state management technique and use it with controller or view?

  • How does the MVC framework handle async data access? What about server side redirects?

  • When and where can I download the bits for the MVC Framework? :)

  • At 2 p.m. (local time) I opened this article. There was one comment. Now we have 6 p.m. and there is many, many, many more comments. This says something.

    Sice some time it's even not a question 'to be or not to be', this is 'how fast to be' :-)

  • This is pretty cool. I can't wait to start using it. I love how it sets you up for success straight from the "New > Project" starting point.

  • ASP.NET MVC looks absolutely brilliant!

    Should we expect any difference in performnace between MVC and WebForms model?
    Will VWD Express support MVC application templates?

    Thanks!

  • From being used to a 3-tier pattern of design, I'd have put the model in a separate project. In fact, I'd probably have put the controller in a separate project to the view too - the way you have it your Model needs references to System.Web, etc. in order to compile.

    Can you say why you chose to have them in folders in one project rather than different projects for each of the three components of MVC?

  • Scott,

    Great stuff. A few comments I think 1 that someone mentioned...

    1. View / Model / Controllers should be seperate projects! Or at least have a template for this. (I woudn't even want the template to create my "model" project because I may already have one, or be using LLBLGen, etc.) This would allow for 2:

    2. There should be a way to plug this into a windows app too. The renderview stuff should be a factory that supports rendering a windows for also.

    3. Seperating the Controllers/Model into class libs would allow for a WPF service layer that the controllers can interact with in order to distribute that app into physical tiers such as Web Server / App Server / Db Server.

    Thanks... hope you guys take feeback to heart!

    BOb

  • This is, by far, the best post I've seen about the upcoming ASP.NET MVC framework. I'm really excited to start using it now.

    I'd be interested to see some examples of how Atlas will mesh with MVC (if at all). Will the UpdatePanel be updated to somehow work with MVC? Will page methods be replaced with some sort of "controller method" calls?

  • Scott,
    You talk about setting up the url mapping rules in the Global.asax (Application class)... and the same seems to be true of the samples I've seen from ScottHa and Phil "that's hott" Haack. So my question is, what happened to having these values configured via a standard .config file?

    Can you shed a little light on why the decision was made to move the rules into the App Class? I'm sure there are good reasons... or maybe I shouldn't be asking such questions of such early, likely in-flux, bits. :)

    Thanks!

  • This is great. But how do I get ahold of this?

    What does this require to deploy? IIS7? Do I just drop something in /bin, or does the server need to be configured?

  • I think the views should not use aspx or ascx, how about "asvx" and pull out all the unnecessary control, usercontrol and page logic that is no longer needed.

  • Can't wait to use the framework, is there an ETA on the CTP?

    Thanks!

  • Scott, nice job, but I've an important question that decide the use or not of this MVC AspNet fwk.
    My applications in .NET works with "3 layers" pattern (business logic and data access in your own dll). How can i use this wonderfull MVC with my Models (data access) and Controllers (B.Logic)?? Because if i'm not reuse this, i've repeat code in every layer; then this MVC is not DRY (don't repeat yourself) and the community don't accept.

    Others programmers put the point in this problem :

    Martin H. Normark said "I like the level of abstraction and seperation, which is something I've always done in the past by having 3 projects inside Visual Studio. One for data access, one for business logic and a website project for UI." and
    Mike Bosch said "1. Wouldn't it make more sense to separate the models and controllers into their own class libraries?"

    PLEASE Scott, give us a response for this important thing. Thanks in advance.
    (Sorry for my latin-english...)


  • Hi Scott,

    I'm very excited to see this once it is released. Until then, any chance of you coming to devteach in Vancouver (Nov 26 - 30) to give a demonstration similar to the one you did for alt.net?

    -Shane

  • Does anyone have a run down on the differences between Monorail and the ASP.NET MVC framework implementations?

  • Scott;
    I love this product. It makes web programming a pleasure.
    Now if we could have similar pattern for SL, I'll be in heaven. BTW, I had a dream last night that SL 1.1 beta will be out end of November...
    ..Ben

  • I would like to see how to use submit buttons now rather than anchor tags, the new API for the anchor tags is awesome so there must be some new functionality on the other controls used for submitting pages to the server. What about normal controls that expose postbacks, how does the WebForms controller interact with the MV Controller in that situation?

  • Thanks Scott!! Can't wait to use it. We are already planning new applications that we will develop using MVC. I think this is the right way to do things... “separation of concerns”, which is what makes the application maintainable and scalable. For a growing business this is absolutely a must!!

  • How does a sitemap control work here?

  • I'm in the process of refactoring our mobile framework into a MVC, and I'd like to use the new MVC framework. However, our View is XSLT. Is the framework extensible, so that we can enable it to support XSLT?

    Thanks!
    Ryan

  • Wow, well done Scott. ;-)

  • Sorry, but I don't see the "halleluja" with this MVC hype. This will make web applications sooo much better because ...??? What? To me the MVC hype (yes, I stick with the term) is to the ASP.Net (or dev in general) what IPhone is in the telecom world. It's slick, it definitively got it's fan masses, but it brings nothing special to the table (oh, come on - i mentioned it was slick, but other than that???). To me it seems like everybody must drop whatever they are doing and catch the MVC train or forever be lost in their pitful caves - this is not true! ASP.Net lets you implement sane solutions as is, and be warned - MVC does not add cerebral cells to the developers brain!

    Sorry, but this doesn't beat sliced bread!

  • I can't wait to get to try this out. The default RoR style url mapping (/[controller]/[action]/) can be changed?

  • Hey Scott,

    This is great, can't wait for part2 nor can I wait for the release. How does this compare to the Patterns & Practices MVC solution??

    Thanks,

    Joe

  • How is this different then UIP (which is MVC)?

    What does this provide that you couldn't do in WWF or UIP?

    When would you use UIP vs WWF vs this new implementation of MVC?

    When would you not use this?

    What are the cons of using this? I.E. what is this increased complexity gaining you?

    For testing, how does this allow you to ensure HTML is generated correctly? I.E, what makes it different than creating a web application and testing the code behind methods that are generic (that don't render anything) and using Web Unit Tests on the rest?

  • Hi Mohammed,

    >>>>> This is amazing, would it be possible for you to demonstrate this part in a screencast or maybe next part? Or something like create a blog in 15 minutes?

    Yes - we'll be publishing some screen-casts like we do for other ASP.NET technogies on www.asp.net in the future. My blog post above only scratched the surface of some of the MVC features - you can obviously do a lot more with it.

    Stay tuned for more details,

    Scott

  • Hi Mohamed,

    >>>>>>>> Have you and the team any plans of including something like scaffolding? where by pointing at a database table clean basic code would be generated for listing,viewing,adding,editing,deleting etc.? This would be a great kick start for beginners like me.

    Yes, the ASP.NET MVC framework will have built-in support for scaffolding. I'll be blogging about this more in the future.

    Thanks,

    Scott

  • Hi John,

    >>>>>>>> Thanks for the post. Since it is early days for this project and SL 1.1 is still in Alpha, are there any plans to allow us to use this MVC model for SL applications?

    Yes, this is something we are looking at. Silverlight 1.1 will have rich binding support for UI which enables you to bind against model objects. This provides a nice way that you can have a controller work against model data, and then have the UI automatically update when the model data changes. I'll cover this more in a separate Silverlight tutorial series in the future.

    Thanks,

    Scott

  • Hi Bill,

    >>>>>>> Can I only pass one object to the View via RenderView or is there a mechanism to pass multiple objects/value types? I'm guessing the convention is to lead me towards an 'interface per view' contract that specifies all data that will be made available?

    You can pass any container object you want to the RenderView method. This container could contain multiple sub-properties. For example I could create a ProductsviewData object that encapsulates multiple values:

    public class ProductsViewData
    {
    public string CategoryName { get; set; }
    public List Categories { get; set; }
    }

    and then pass this to RenderView to send multiple data results to the view.

    Hope this helps,

    Scott

  • Hi Daniel,

    >>>>>>> Where or when can I download the CTP?

    We'll have the first public CTP in a few weeks. Not far off now.

    Thanks,

    Scott

  • Hi Stuart,

    >>>>>> I have one question: What was the reasoning behind having Html.ActionLink as opposed to a more standard ASP.NET type approach of an control? Using methods that generate strings of HTML seems like a step back from the server control architecture that makes ASP.NET so cool in the first place. Of course it would be trivial to write an ActionLink server control that calls Html.ActionLink in its Render method. Have you considered including something like this?

    The first CTP only has the helper methods, but our plan is to ship server controls that correspond to them in the future as well (the server controls would be built on top of the methods). That way you can use either approach.

    Hope this helps,

    Scott

  • Hi Jonathan,

    >>>>>> Great article, can't wait to try it out. On a seperate note, any hint on when VS2008 will rtm?

    VS 2008 will RTM very, very soon. We've publically said it will be by the end of November - stay tuned. :-)

    Thanks,

    Scott

  • Ho Rob,

    >>>>>> While you are talking about mocking objects for TDD, would you consider including how to mock out any orm being used.

    One approach you can use would be to create a INorthwindRespository interface that you have NorthwindDataContext implement. This would have the three retrieval methods I created in the partial class. You'd then use this interface reference within your ProductsController when retrieving data, and probably set it via dependency injection when the controller is created.

    The benefit would be that you could then mock out implementations of this INorthwindRepository interface in your unit tests - which would allow you to test the ProductsController without having to actually talk to a database.

    I'll try and show a sample of this in the future.

    Hope this helps,

    Scott

  • Hi Steve,

    >>>>>> Since it adds a testing project, does this require Team System?

    No - the good news is that Test Projects with VS 2008 are now supported with the VS 2008 Professional edition - and no longer require team system.

    You will also be able to use the VS Express and Standard edition products as well, and then use NUnit, MBUnit or some other testing framework with them (we'll ship project templates for these as well).

    Hope this helps,

    Scott

  • Hi Mike,

    >>>>>>> I have some questions that I hope you can answer:

    >>>>>>> 1. Only Web Application model will be supported, not Web Site?

    We'll support both web application projects and web-site projects. In general you'll find that if you are using unit testing that web application projects work better (since you can load the project assembly and directly test it), but the runtime behavior will work with both.

    >>>>>>>>> 2. Is it also possible to have this URL mapped: /Products/Beverages/3 instead of /Products/Beverages?page=3 or does it _need_ the parameter name?

    Yes - this is totally supported. Just set a route rule for /Products/Beverages with the format /Products// - they'll then get passed in as arguments to the action method:

    public List(string category, int? page) {

    }

    >>>>>>> Also, some ideas and general remarks:

    >>>>>>> 1. I'd love to see more helper methods for use in the views, I like how Ruby on Rails has many shortcuts for creating forms and formfields etc.

    Yes - we'll have a rich library of helper methods for the views. They'll include helpers to create all the standard forms, formfields and more.

    >>>>>>>> 2. Migrations! Not a part of MVC but from my experience with Ruby on Rails I would love to see support for this somewhere, anywhere! It would fit perfectly with the more agile way of developing that is possible with ASP.NET MVC.

    Rob Conery is building .NET Migrations support as part of the SubSonic project, and recently joined Microsoft. You'll be able to use this with ASP.NET MVC.

    Hope this helps,

    Scott

  • Hi Andy,

    >>>>>> Feature request - please please include a comparable feature to the Castle MonoRail SmartDispatcherController that automatically binds to Post variables submitted by form elements such as and . Or is this sort of functionality what you see the current frameworks providing on top of Microsoft MVC?

    Yes - we'll be supporting this feature with the final release of ASP.NET MVC as well.

    Hope this helps,

    Scott

  • Hi Timo,

    >>>>>>> What about Web Parts, are they supported ? Is it possible to develop Web Parts by using MVC ?

    We don't support web parts within MVC views today. You can have a WebPart hosted inside of a standard ASP.NET WebForm that does an AJAX call to a MVC view to refresh its HTML content, and so you can integrate MVC with WebParts. But you can't host a webpartzone directly inside of a MVC View.

    Hope this helps,

    Scott

  • Hi Gary,

    >>>>>>> Where I can download source code for this post?

    My plan is to get a little further along with a few posts, and then post the sample code for the e-commerce site once we ship the first public preview of the MVC bits.

    Hope this helps,

    Scott

  • Hi Scott S,

    >>>>>>> What would happen in your products detail example when the user changes the product id in the url to something that isn't an integer such as "/Products/Detail/ABC"? Will an exception be thrown since the ProductsController.Detail method is expecting an int?

    You can handle this scenario in a couple of ways.

    1) One would be to add a condition to your URL routing registration to route the URL differently depending on whether the parameter is a string or integer (the URL route system is flexible enough to handle these differently - and even map them to different controllers/actions depending on the value).

    2) Alternatively you could mark the parameter to be nullable on your action method. If you try to assign "ABC" to a nullable integer, the value passed in would be null. You could then add your own logic to decide what to-do then.

    3) Alternatively if you have your action method just marks the variable to be an int, then the framework will raise an error if the user tries to pass in "ABC" as the value. You can then choose to handle this error and display whatever error you want to the end user.

    Hope this helps,

    Scott

  • Hi Vkl,

    >>>>>>> Is it possible to test drive view in isolation, i.e. render it without full ASP.NET pipeline? It's necessary thing when using TDD for web development.

    For the first public preview CTP you need to host ASP.NET to unit test views. You can still isolate them from your Controllers - but it does require an ASP.NET app domain to test them. We are looking at whether we can enable isolated unit testing of the views independent of the ASP.NET app domain in the future though.

    Hope this helps,

    Scott

  • Hi Vijay,

    >>>>>>> How do you put the List page parameter into the core URL like you did with the category string? I guess I'm asking where you can define more comprehensive routing rules.

    Yes - this is totally supported. Just set a route rule for /Products/List/Beverages/3 with the format /Products/List// - the category and page index will then get passed in as arguments to the action method:

    [ControllerAction]
    public List(string category, int? page) {

    }

    >>>>>>>> Can you map a nullable type to a url segment? like /Products/List/CatName/23 and can you leave it blank like this /Products/List/CatName/?

    Yes - this is totally supported. You can also optionally define "default" values in the route rules to use in the case that the value is null.

    Hope this helps,

    Scott

  • Hi Mike,

    >>>>>>> I'm also very keen to get my hands on the CTP. Scott, you mention, using Inversion of Control containers with the MVC framework. I'd be very interested in seeing a blog post on this subject. Also, will there be a sample application (with tests and IoC) available alonside the CTP?

    We have a IControllerFactory extensiblity point that owns creating Controller instances. You can use this with a IOC container to customize any Controller instance prior to it being called by the MVC framework. We'll be posting samples of how to use this with ObjectBuilder and Windsor with the first CTP I believe.

    Hope this helps,

    Scott

  • Hi Daniel,

    >>>>>>> Very cool! One thing I'd like to see guidance on is developing MVC apps with multiple UIs. You say here that it's best to put your models and controllers in the web app, but say we want a Winforms, WPF, Silverlight, and Web UI all doing similar things. Or a Mobile Web UI and Desktop Web UI... Would these still each need their own Models and Controllers, or does it make sense to have one library that they all share? If so, how is that supported? I'm still new to MVC, so if I'm missing something conceptually here, tell me!

    That is a good question, and one we'll need to provide more guidance on in the future. In general it is often hard to share the same controller across both client and web UI, since the way you do data access and the stateful/stateless boundaries end up being very different. It is possible - but some guidance here would ceretainly be useful. My team should hopefully be coming out with this in the future.

    Hope this helps,

    Scott

  • Hi Matt,

    >>>>>> How would you go about populating several data driven dropdown lists as well as loading the page content without putting data access logic in the view?

    In general what you'd do is to to have the controller retrieve the data for the drop-downlists, and then pass them to the view. The View would then either databind them to controls or call an Html.Select() UI helper method to display them.

    I'll cover this more in a future blog post.

    Hope this helps,

    Scott

  • Hi Jeremy,

    >>>>>> I really appreciate this material. Do you support the MVC pattern over the MVP pattern? Or are there just better scenarios for using each?

    The above approach I showed uses a MVC based pattern - where the Controller and the View tend to be more separate and more loosly coupled. In a MVP pattern you typically drive the UI via interfaces. This works well with a controls model, and makes a lot of sense with both WinForms and WebForms where you are using a postback model.

    Both MVC and MVP are perfectly fine approaches to use. We are coming out with the MVC approach for ASP.NET partly because we've seen more demand for it recently for web scenarios.

    Hope this helps,

    Scott

  • Hi Max,

    >>>>>> This looks spectacular! Can you tell us when to expect a (beta) release? Can't wait to try it out myself! :-)

    We'll have the first public preview out in a few short weeks. You will be able to start building (and deploying) apps using the ASP.NET MVC framework then.

    Hope this helps,

    Scott

  • Hi Roger,

    >>>>>> Thanks for the very detailed tutorial and demo of the forthcoming MVC, especially for including the unit test details. Your post would make a super book chapter. I'll be interested to see how you mock LINQ to SQL's DataContext for testing (particularly shopping cart updates).

    I'll add onto my list of things to cover in a future blog post. One approach you can use would be to create a INorthwindRespository interface that you have NorthwindDataContext implement. This would have the three retrieval methods I created in the partial class. You'd then use this interface reference within your ProductsController when retrieving data, and probably set it via dependency injection when the controller is created.

    The benefit would be that you could then mock out implementations of this INorthwindRepository interface in your unit tests - which would allow you to test the ProductsController without having to actually talk to a database.

    >>>>>>> When can we expect a similar chapter with SubSonic as the DAL and scaffolding provider? (see oakleafblog.blogspot.com/.../subsonic-will-be-toolset-for-microsofts.html)

    I'll be covering scaffolding in a future blog post. LINQ to SQL scaffolding is built-in with ASP.NET MVC and doesn't require SubSonic. SubSonic will also obviously be adding new ASP.NET MVC features as well.

    >>>>>>> P.S. Posted at 3:45 AM? When do you sleep?

    4am-7am was my sleep period today. :-)

    Thanks,

    Scott

  • Seriously Scott... Get some sleep!

  • Scott;
    Does this mean that with MVC, we no longer use LinqDatasource in the View section?

  • Great stuff - looking forward to the bits with great anticipation.

    Any word on when there will be a Go-live license available?

  • Perhaps I missed it somehow, but can you explain on which version of asp.net will this ctp run?

  • Excellent information on the MS MVC Scott. Fantastic work so far - I'm quite impressed.

    I love the testing support, the 'familiarity' aspects as well.

    Great job - I look forward to some seeing some bits soon :)

  • One question: Any comments on how AJAX support will be implemented with this model?

  • Scott, this is amazing timing! The URL mapping features inherit in an MVC application are PERFECT for the upgrade to ASP.NET 3.5 I'm making to my spelldamage.com site. Hosting question, will hosts simply need to support the ASP.NET 3.5 framework to allow us to run ASP.NET MVC applications?

    Also, I'm new to MVC type development. My understanding is there is no longer a postback that occurs. How do you implement button clicks, etc... in the MVC framework?

    Thanks Scott, I can't wait to port my development to this framework.

    Chad

  • Great stuff.
    This form of MVC is much closer to what I think of as MVP than classic MVC because the Model does not talk to the View at all. As this is the main benefit of MVP (as it allows testability easily) what extra would be gained by going "full" MVP? Or have I misunderstood?

  • Hi Mattieu,

    >>>>>>> So the controller deals with the incomming request. If I understand correclty, if I need to add a new "page" to my website I need to modify my controller and recompile the application?

    Correct - Controllers are the entrypoints into the application. So if you want to expose a new URL you'd want to add a new Controller to the application.

    Hope this helps,

    Scott

  • Hi Matthew,

    >>>>>>> It doesn't look like this will work with the ASP.Net AJAX UpdatePanel control. Will you be enhancing ASP.Net AJAX so that it integrates with the new MVC stuff? I can see wanting to hit a url like /Products/Detail/3 and it return just the markup for the detail of that product (or maybe a JSON serialized Product object). Will this be easy?

    The control relies on the control being on a page - which isn't supported with MVC Views.

    What we will have, though, is an easy API that enables you to call back to Controller actions on a server and then inject the response back to refresh a portion of a page. This is a little more work than an UpdatePanel - but it also does give you more control over how exactly the AJAX update takes place.

    Hope this helps,

    Scott

  • Hi Carlo,

    >>>>>> using server side controls I see a problem on handling the control naming convention with MVC framework (actually also with 'normal' asp.net coding). If I have this code

    >>>>>>

    >>>>>> in the calling page, I have to handle a name like

    >>>>>> ctl00$ContentPlaceHolder1$txtMyMessage

    I'll cover using form controls calling back to the server in future posts. With the MVC pattern you'll typically end up declaring your own elements around elements in a View, and work closer to the HTML/HTTP metal.

    Hope this helps,

    Scott

  • Hi John,

    >>>>>>>> Awesome! I con't wait to start playing with this. One thing I'd like to see in a future post is, how are user controls that need a controller going to work? (For example, a data driven hierarchical menu that might live in the left pane of a web site.)

    You'll be able to have user control views call back to Controllers on the server and incrementally update regions of a page this way. We'll cover this in the future in upcoming blog posts.

    Thanks,

    Scott

  • Hi Sondre,

    >>>>> The ASP.NET MVC Framework is looking good, but I'm unsure how this will fit into custom MOSS 2007 development. Are you taking into consideration that we would like to use this framework for custom development ontop of MOSS? MOSS includes it's own URL rewriting/handling, I expect that to create problems for this new framework. Are you considering support and implementation on MOSS - this is important for a lot of companies as more and more solutions are being development on that platform, and not from a scratch with an empty ASP.NET solution.

    SharePoint support will definitely be something we look at in the future. We don't have a plan we are ready to talk about yet with it right now - but it is something we'll work on.

    Thanks,

    Scott

  • Hi MikeBosch,

    >>>>>> 1. Wouldn't it make more sense to separate the models and controllers into their own class libraries?

    Yes, this is ceretainly something I'd recommend for larger projects.

    >>>>>> 2. Will all the MVC features be available in VS 2005?

    Right now the ASP.NET MVC features work on top of .NET 3.5 - so you'll want to use VS 2008 to target them.

    >>>>>>>> 3. How come URL rewriting is managed in the Global.asax? Can this be managed from within a IHttpModule?

    I'll cover the URL routing infrastructure in a future blog post. In general you register rules at application startup, and typically use the Application_Start event to register them. The MVC framework then handles all of the logic necessary to process them.

    >>>>>>>> 4. How about making the action to execute a property of the [ControllerAction] attribute so it doesn't depend on the method name? For example, [ControllerAction(Action="Detail")]

    While the default routing rule uses the method name to execute the action, this isn't required. I'll show how you can customize the routing rules so that the method name doesn't have to match the URL name.

    Hope this helps,

    Scott

  • Hi John R. Lewis,

    >>>>>>> It would be great to see an example of a round trip from a read only list view page, to a form using whatever the framework uses for databinding, and back to the list view.

    I'll add this to the list to blog about.

    Thanks!

    Scott

  • Hi Matthew,

    >>>>>>>> How is input validation going to work? Is there a place in the controller where you can register validation errors and then access them from the view similar to the ViewData property?

    I'll cover some strategies for how you can handle errors within applications in future posts.

    Thanks!

    Scott

  • Hi Ray,

    >>>>>>> Great article! I have 2 quick questions, one is that when you built the view, you have an approach Using Inline Code which got intellisense, do you recommend using this approach? Compare this to using the server control in this particular snippet of example, it looks shorter and cleaner than server control. Second question is in which one of your LINQ tutorial did you discuss caching? Basically, when user browse your catalog the first time the Model got the data from DB and should cache it for a while on server, right?

    I haven't covered caching with LINQ to SQL yet (so much to still blog! )

    Whether to use inline code or server controls in your views typically comes down to personal preferences. Some people find inline code more natural, some prefer more of the code/content separation that server controls provides you. In general I typically recommend that you use whichever feels best to you.

    Hope this helps,

    Scott

  • Hi Scott,

    I haven't seen any examples of routing information in a config file since your earlier ALT.NET presentation; all routing information is always shown in the Global.asax now. Are simple routing scenarios via a text config still part of the planned CTP release?

    Troy

  • Hi Hemal,

    >>>>>>> I have questions about state management. where we suppose to put state management logic using ViewState or Session. Will it be going in aspx page(view) or in Controller? if we use it in View, we are trying to control something and according to MVC pattern it should be in controller. If we put it in Controller, our view and controller both become tightly coupled with each other, which creates some contradiction.

    I'll cover the state management options provided by the MVC model in a future post. There are a couple of options available (Session state is one - we also have a TempData object that you can use to temporarily store values across redirects).

    Hope this helps,

    Scott

  • Hi Igor,

    >>>>>>> Should we expect any difference in performnace between MVC and WebForms model?

    No - in general you'll find both about the same in terms of performance.

    >>>>>>> Will VWD Express support MVC application templates?

    Yes - we'll support using the MVC option with VWD Express as well as Visual Studio.

    Thanks,

    Scott

  • Hi Tim,

    >>>>>>> From being used to a 3-tier pattern of design, I'd have put the model in a separate project. In fact, I'd probably have put the controller in a separate project to the view too - the way you have it your Model needs references to System.Web, etc. in order to compile.

    You can definitely put the models in a separate project as well. For larger projects I'd definitely recommend splitting the application across more than one project.

    Hope this helps,

    Scott

  • Hi Dave,

    >>>>>>> I'd be interested to see some examples of how Atlas will mesh with MVC (if at all). Will the UpdatePanel be updated to somehow work with MVC? Will page methods be replaced with some sort of "controller method" calls?

    I'll be covering this in future blog posts. We'll have a good ASP.NET AJAX integration story with the MVC model.

    Thanks,

    Scott

  • Hi Steven,

    >>>>>>>> You talk about setting up the url mapping rules in the Global.asax (Application class)... and the same seems to be true of the samples I've seen from ScottHa and Phil "that's hott" Haack. So my question is, what happened to having these values configured via a standard .config file?

    >>>>>>>> Can you shed a little light on why the decision was made to move the rules into the App Class? I'm sure there are good reasons... or maybe I shouldn't be asking such questions of such early, likely in-flux

    In general it is sometimes easier to reflect routing rules via code than configuration (and you get compile-time checking with them). Having said that, you ceretainly could load the routing rules from a config file if you preferred it that way.

    Hope this helps,

    Scott

  • Hi The Other Steve,

    >>>>>>>> This is great. But how do I get ahold of this? What does this require to deploy? IIS7? Do I just drop something in /bin, or does the server need to be configured?

    The first MVC CTP will be a separate install you can run on a machine. We'll then role it into a .NET Service Pack in the future. It will work on both IIS7 as well as IIS5/6.

    Hope this helps,

    Scott

  • Hi Jorge,

    >>>>>>>> My applications in .NET works with "3 layers" pattern (business logic and data access in your own dll). How can i use this wonderfull MVC with my Models (data access) and Controllers (B.Logic)?? Because if i'm not reuse this, i've repeat code in every layer; then this MVC is not DRY (don't repeat yourself) and the community don't accept.

    There is no need to put your business and data logic in the same assembly as your controllers. You can split them up across multiple class library projects if you prefer.

    Thanks,

    Scott

  • Hi Shaneo,

    >>>>>>> I'm very excited to see this once it is released. Until then, any chance of you coming to devteach in Vancouver (Nov 26 - 30) to give a demonstration similar to the one you did for alt.net?

    I wish I could, but unfortunately I won't be able to this year. :-(

    Sorry!

    Scott

  • Hi kidsyco,

    >>>>>>> I would like to see how to use submit buttons now rather than anchor tags, the new API for the anchor tags is awesome so there must be some new functionality on the other controls used for submitting pages to the server. What about normal controls that expose postbacks, how does the WebForms controller interact with the MV Controller in that situation?

    You can also use Buttons to post back to the server. I'll show how to-do this in future blog posts.

    Thanks,

    Scott

  • Hi Edmund,

    >>>>>>> How does a sitemap control work here?

    You can use the SiteMap API from both the Controller class and Views.

    Hope this helps,

    Scott

  • Wow, ASP.NET on Rails! Great!

  • Hi Jesse,

    >>>>>>> 1. Can you dynamically adjust the master page/layout for a view at runtime? If the view is responsible for setting the layout then it seems like there would be no way to adjust that at runtime without having the logic in the view. Seems like the controller should have the power to adjust the layout/master page.

    You can optionally configure a default master to use within your view (like you do today with .aspx pages). Controllers can also programmatically change the master of a view when you call the RenderView method.

    For example:

    RenderView("MyView", product, "MyMaster");

    >>>>>>> 2. What does viewData become if I need to pass multiple data values to my view? Would I pass a dictionary instead? If so then I think the framework should have better support for passing multiple values to the view?

    You can either pass in a dictionary, or a class with multiple properties with sub-objects.

    >>>>>>> 3. Will there be anyway to specify a different name for a controller or action that will still use the default routing rule? For example on my own custom asp.net mvc framework, I can specify this attribute property on a controller so that the routing engine can find it by a different name than the actual class name: [Controller(Name="about-us")]. Obviously I cant create a controller class called about-uscontroller, so the attribute property solves this problem for me if I want my url to be like this /about-us/contact-us. I have the same kind of attribute property for an action [Action(Name="contact-us")]. That way I dont have to add routing rules and I get full flexibility in how I name my controllers and actions.

    You can either change the routing rules to accomplish this, or alternatively you can apply an attribute based filter to modify the URL mapping. This gives you a lot of flexibility in terms of mapping the URLs however you want.

    >>>>>>>> 4.Will validation controls still work correctly with this framework?

    The existing controls require postback support, so won't work within MVC views. We will have validation helpers that you can use though that are MVC aware.

    >>>>>>>>> 5.Does an action have a default view or must you always call RenderView?

    Actions don't by default have default rendering semantics. You can add this support to make it automatic, but by default no default rendering happens.

    Hope this helps,

    Scott

  • Great stuff.
    This form of MVC is much closer to what I think of as MVP than classic MVC because the Model does not talk to the View at all. As this is the main benefit of MVP (as it allows testability easily) what extra would be gained by going "full" MVP? Or have I misunderstood?

  • Hi Evan,

    >>>>>>>> I can't wait to get to try this out. The default url mapping (/[controller]/[action]/) can be changed?

    Yes - you can completely change the default rules however you want.

    Thanks,

    Scott

  • Thanks for the post. Was very helpful

  • Hi Ray,

    >>>>>>> Hi Scott, based on this URL mapping scheme, is the MVC approach good for large sites or it's intended for small to medium sites? If for example I defined a url path mysite.com/.../5, then later on I changed my mind and want to call it http://mysite.com/prod/l/5, do I need to change my controller C# code and re-compile? Thanks!

    Because URL routing rules are configured in one place (the route engine), you can make a change there and automatically have all controllers pick up the change.

    Hope this helps,

    Scott

  • Hi Ben,

    >>>>>>> Does this mean that with MVC, we no longer use LinqDatasource in the View section?

    While the LinqDataSource control will technically work in MVC Views, if you are using a MVC model you wouldn't want to place it there. Instead you want to perform all of your data and application logic in the Controller layer - and then pass the needed data to the view.

    Hope this helps,

    Scott

  • Hi Kevin Dente,

    >>>>>>> Any word on when there will be a Go-live license available?

    The first public MVC CTP will support deploying apps (we won't disallow this).

    Hope this helps,

    Scott

  • Hi Dragon,

    >>>>>>> Perhaps I missed it somehow, but can you explain on which version of asp.net will this ctp run?

    The MVC framework builds on top of .NET 3.5

    Hope this helps,

    Scott

  • Hi Steve,

    >>>>>> One question: Any comments on how AJAX support will be implemented with this model?

    We'll cover this in more depth in future posts. In general you'll be able to call back from a client to a Controller action and send back either data or HTML that you cna then use from JavaScript on the page.

    Thanks,

    Scott

  • Hi ChadT,

    >>>>>>> Scott, this is amazing timing! The URL mapping features inherit in an MVC application are PERFECT for the upgrade to ASP.NET 3.5 I'm making to my spelldamage.com site. Hosting question, will hosts simply need to support the ASP.NET 3.5 framework to allow us to run ASP.NET MVC applications?

    Your hoster will need to support .NET 3.5 for the MVC support.

    >>>>>>> Also, I'm new to MVC type development. My understanding is there is no longer a postback that occurs. How do you implement button clicks, etc... in the MVC framework?

    I'll cover this in upcoming posts. In general you'll find that the MVC model has you working closer to the underlying HTTP/HTML protocols. So to implement button posts you'd typically wrap your own element on the page and set the action attribute to point to a controller action method.

    Hope this helps,

    Scott

  • Awesome! We're in the process of migrating from a Java MVC web env to .NET...we can't wait to get our hands on this.

  • This is some good stuff. This seems much easier to use then the stuff coming out of the P&P team, and just as powerful.

    How would someone go about helping out on a project like this. Either in their spare time or possibly full time ;)

  • "I'll blog more about this in the future." You get paid by the word right? Awesome post as I sit here salivating over the bits I don't have yet. Sigh.

  • Hope you get all the performance tests going as wonderfully as well. If VS2008 is as fast as Eclipse that'd certainly do it good.

  • Thanks for the quick response Scott. Since I'm an MVC noob, I can't wait to see how data gets passed back to the controller for processing. For example, if I had a textbox and button control on the page that I intended to allow the visitor to enter some text into a DB with... how would the data get back from the view to the controller for processing? Can't possibly be by querystring... ;)

  • It's Dragan, not Dragon, but this is OK. :) Thanks, again

  • Thanks for answering all the questions!

  • Scott,

    You wrote above that ASP.NET MVC will run on IIS7 as well as IIS5/6. Then you wrote that "Your hoster will need to support .NET 3.5 for the MVC support.".

    If .NET 3.x isn't supported on Windows 2000 how can IIS5 host MVC?

    Thanks,
    Hans

  • This looks great

    One question. You say it is MVC but it looks more like MVP to me in that the Model does not talk to the View (which I believe is the bit that makes it testable). What extra does "full" MVP give?

  • Great topic, especially with all the q&a going on.

    One other thing I am wondering about is this: If your masterpage needs data based on application logic (or a user control for that matter), how can they get the data if the controller that is handling the request is specific to the view (ProductsController)? Can the masterpage trigger it's own controller somewhere along the way to get the data it needs?

    Also, how do you feel about the enthusiasm around this framework? I understand it's really cool to make something that so many people want, but it also means that many people are not happy about webforms. Any regrets, that maybe it should have been this way from the beginning and you would have had more mindshare?

    Thanks!

  • Awesome post Scott, i truely can not wait to try this out! Keep it comming!

  • Dear Scott,

    While testability is a great thing, I believe one of the other advantages using a MVC framework is making the presentation code reusable. It seems this advantage is lost in this framework ( Asp.Net MVC ? )

  • What does SKU mean?

  • Hi Scott,

    >>>>>>> You can use the SiteMap API from both the Controller class and Views.

    How does the SiteMap API integrate with the new dynamic urls that comes with MVC? The Web.sitemap file is pretty static?

  • This looks really interesting...

    I realize it's still early, but I'm interested in how the URL parsing logic validates input with respect to parsing types.

    For example, if I get a request similar to /Products/Detail/somestring, where some string is not an int, I might return a 404 or a 400. The same applies to /Products/Detail?id=somestring.

    How does the URL parsing logic handle this and how customizable is this?

  • Scott,

    Could you please list the things that we would miss in the MVC framework that we already have in webforms framework (like postback and validation)
    Thanks

  • I would like to ask if the MVC framework supports string token replacement template? So that even not a programmer can design/edit the template and plug it into the MVC framework directly?

  • >>>
    >>>>>> One question: Any comments on how AJAX support will be implemented with this model?

    We'll cover this in more depth in future posts. In general you'll be able to call back from a client to a Controller action and send back either data or HTML that you cna then use from JavaScript on the page.
    <<<<<<<<<

    Kind of confused here. Wouldn't sending HTML from the control for AJAX be a bit messy since it would relate more to the view? Am I missing something?

    You also mentioned about State in a tempData, would this in some way preserve the state of data controls on the page during the cycle of validating it and posting errors, so that the user can repost the form without entering all the data over again? Also, how would this "State" handle if the user using the back buttton to go to the previous page.

    I can see how the MVC will work with sites displaying information, but I do not see how it will handle data entry type sites very well. I assume that information is coming in Part 2? :)

  • Looks like great stuff, Scott. Looking forward to the next post. Keep up the good work.

  • I want my...
    I want my...

    MVC

  • Scott, thanks for the fast reply. You'll probably answer this in a future post, but in the ASP.NET MVC framework, how does user entered data (such as from a textbox control, etc) get returned to the controller for processing? Surely it's not by querystring. :D

    Also, will the URL routing engine support a URL like this, www.domain.com//// where var1,2, & 3 are passed to the controller?

    Thanks!

  • you sould use GIF's files for screenshots.

  • Hi Scott
    Very nice feature but I have a question is "ASP.NET MVC Framework" will be shipped with visual studio 2008 or sometime later?
    Thank you for your cool way in explanation this is what we cool in Arabic "السهل الممتنع" it can be translated to "the easy thing that can not everyone do".
    Go for more please

  • Hi Scott,

    First thank you for all the work.
    I learned Rails last year but never used it because it was missing features i liked too much in .NET, but it was time well spent and now we get the best of both worlds.
    In the 'feels like Rails' topic, I did not see anything about the Flash, is there?

  • Hello Scott,
    Thanks for all the work.
    I did not see anything about the Flash, is there?

  • Hi Scott, from the first glance, would be a possibility to not use inheritance for aspx page classes? I'd rather implement the interface really in that case, and I'm sure you know why I want that :)

    You got many questions about controls, well it's obvious that with the model you have, we must have some replacement. I'm very concerned, how do you see the implemention of UI bricks in that model? Call them 'controls' or anything. Even having nested masterpages is, in my opinion, not enough to replace controls as reusable functional parts of UI.

    If we don't have controls, we don't have current themeing engine, and so on, and so on. Perhaps you could write a post not about doing concrete things with your MVC framework, but rather describing a concept, how do you develop with that in general, and how do you refactor current ASP.NET applications to fit in that model.

    Thanks anyway for a great job, was a pleasure to visit your presentations in Seattle this march :)

  • This smells a lot like Ruby on Rails. *winks* And I like it.

  • Dear Scott,
    Excited to see the new model, but my idle brain too many questions.
    How to integrate MVC architecture with WCF, can I use Controller classes as my ServiceContracts also?
    Does the routing engine is similar to WF, can I use workflow within MVC model?
    Are you planning a seperate post on addressing AJAX postback calls?

  • So, this is all really nice and neat... but all about HTTP-GET so far, what about HTTP-POST? I'm not talking about "classic" ASP.NET postbacks, but what would it look like when you fill out a form and post it to the server in order to create or update data?

    thanks

  • Ciao Scott,

    what about asynchronous pages and the new MVC framework?

    Thanks

  • Hi Scott. Just a simple question: it's mandatory to allways call method RenderView? In MonoRail, if there is a view named as the current controller action, that view will be rendered.

  • Hi Scott,
    Now I got a chance to read all your article. It is great ! Thanks for it.
    But I got some questions to ask you and hope you answer me.
    1) In the article, you demonstrated one-way relation between Models and Views - namely from Views to Models. How about from Models to Views ? Models change, View should be changed ! Please cover this in the future parts.
    2) Could you talk more about RenderView() implementation in particular how Controllers pass data to Views ?
    3) Since controllers handle web flows, How the MVC framework deals with BACK and FORWARD buttons of web browsers ?

    Thank you once again.

  • I think you were answering other questions when mine got posted. I'm really trying to get a good feel for this new technology.

    How is this different then UIP (Microsoft Patterns and Practices) (which is MVC)?

    What does this provide that you couldn't do in WWF or UIP?

    When would you use UIP vs WWF vs this new implementation of MVC?

    When would you not use this?

    What are the cons of using this? I.E. what is this increased complexity gaining you?

    For testing, how does this allow you to ensure HTML is generated correctly? I.E, what makes it different than creating a web application and testing the code behind methods that are generic (that don't render anything) and using Web Unit Tests on the rest?

    I think these are valid questions. As the GoF and Fowler write in their books (sometimes abstractly); patterns are more than just 'recipes' to writing software, an important aspect of using them is knowing when to use them, and more importantly when not to.

    Or too put it simply; don't serve the President a PBJ, but at the same time don't create a four coarse meal when all you're having is brunch with your mother.

  • Scott, Thanks for tutorial.

  • I wonder if it is similar to what Spring Framework is doing? www.springframework.net

  • Hi QiangLi,

    >>>>>>> I am using VS 2008 Beta2 now. How create a new ASP.NET MVC Web Application in VS 2008 beta2?

    We haven't released the first preview of the MVC framework just yet. We will shortly though.

    Thanks,

    Scott

  • Hi ChadT,

    >>>>>> I can't wait to see how data gets passed back to the controller for processing. For example, if I had a textbox and button control on the page that I intended to allow the visitor to enter some text into a DB with... how would the data get back from the view to the controller for processing? Can't possibly be by querystring...

    At a high-level, for form input you'd direct your form element to post to an action on your controller. Your action can then map the incoming parameters as method arguments. I'll cover how to-do this in a future blog post.

    Thanks,

    Scott

  • Hi Scott,

    This is great stuff! I can't wait to give it a try. I would love to see a post about authentication/autorisation with the MVC framework. I guess forms authentication can't be used here...

  • Hi Scott,

    Do you have any plans on implementing support for postbacks? This looks really interesting, but I don´t really know why I should use this instead of the "normal" way with postbacks.

    Can you post some examples where you post data instead of just showing it?

    Cheers,
    Mikael Söderström

  • What version of the .NET framework is being targeted by this MVC?
    I wish it will be .NET 2.x, since it might still be difficult getting
    some customers to the .NET 3.x soon.

    Best regards,
    Paul.

  • Looks fantastic, I will try it in my web project. I’m looking forward to your next part.
    One question for you, it seems like all classes are located into ‘Models’ folder. Is that means all business logic and data access classes need to be coded in Models? The ‘App_code’ folder is not necessary for MVC framework?

  • Mr. Scott;
    >>At a high-level, for form input you'd direct your form element to post to an action on your controller. Your action can then map the incoming parameters as method arguments. I'll cover how to-do this in a future blog post.<<

    Question on your comment: So, if we are directing data from the form the elements to controler (via passing them as parameters to the methods in the controler), then I guess the old concept of ASP.Net data binding with input fields are out the door. Which means, we are in charge of getting the data from input fields, sending them to controler and then the methods in the controler decide how and where that data should be saved? Did I undrestand you correctly? It's almost like we can treat the controler as a "Web service" concept when using Silverlight as the front-end? Wow, things are getting nice and structured...

  • Very Very Very GOODDDD
    Thanks

  • A discussion today around 'Wizards' occurred, I'd like to hear how a wizard with a 'back' button would be handled with MS MVC.

  • In response to dougramirez's comment about rules being on the model...

    I've found that sometimes the rules belong on the model, and sometimes they don't. The pattern that I've liked using with my MVP pattern is to have a Business Manager class for each Data Model. Keep the Data Model classes as simply that -- data model/container. Then implement a Business Manager for the data model entity to perform all actions against the model. Then, when you have multiple controllers that work against a particular data model entity, they all go through the same manager.

    As for data entry validation and security and whatnot though, I still put the responsibility for this on the controller, as this is presentation logic, not business logic. You can easily find a scenario where the same data entity field can be shown on 2 screens, and on one screen the field is required, but on another, it's not. With field validation on the data model, this scenario would be difficult to support.

  • Looking forward to using this with our next generation of applications! Much of this reminds me of HTML::Mason. Thanks for the intro.

  • To Jeff Handley:

    >>>>>As for data entry validation and security and whatnot though, I still put the responsibility for this on the controller, as this is presentation logic, not business logic

    So you mean to tell me that each application in an enterprise has 'to know' that product managers are the only one that have the ability to modify products? So you're going to all the way across multiple network hops just to have 'My custom description of this sku' truncated unknowingly by the database (because it's only VARCHAR(20) instead of telling the user on one hop to the web server that the description is to long...or were you going to catch a SqlException to do that?

    And why would a controller, a mechanism that just decides what to render, have any logic? A controller should be nothing more than a piece of code that does navigation based upon arguments...'X requested, go to Y'; this may come from the view or the model; the view display, the model contains business rules (hopefully using some sort of business logic framework). A controller should be no smarter than your mouse driver.

    As Doug pointed out, this is the perfect reason why guidance needs to be given. I have a feeling only 1/10th of the people out there using MVC have ever actually looked at the origins of MVC (SmallTalk) and find out how and why it came about. I have a feeling 9/10ths of people would realize they didn't need MVC if they had.

  • Guido:

    What you are talking about is at the asp.net level, not webforms level.

    So yes, authentication would be part of MS MVC since it also sits on top of the existing asp.net framework.

    I think people confuse 'webforms' with 'asp.net' :)

  • I'm really glad Jeff Handley responded to my comment. It's a perfect example of what I meant when I referred to Microsoft introducing technology without proper guidance.

    Jeff describes a very typical mistake made in the "I must have a DAL" world of applications usually designed from an ER model and not requirements. I won't belabor this point. There are some resources available to describe why separating state management out of your business object is rarely ever needed, or used. Rocky Lhotka has blogged about this at length.

    Jeff’s solution is indicative of a common approach by overzealous architects who seem to be getting “paid by the tier”. In Jeff’s solution the controllers have to know about business managers who then have to know about the data models. If you simply put the business rules, validation rules, security, and data access into an object in the model, then you wouldn’t need a bunch of managers, and the controller would simply interact with the appropriate ‘thing’ in the model. If there were more than one controller that needed to interact with a single ‘thing’ in the model, so be it. The ‘thing’ is smart. It knows its own rules, how to validate itself, and to get and save itself. This minimizes the moving parts in the framework and simplifies the development and maintainability of the application through the very simple concept of (drumroll…) encapsulation!

    Data validation and security absolutely do not belong in the controller! Code reuse flies out the window when that happens, and can’t certainly support logical use cases. If a property of an entity is required, in one scenario and not in another, then 1 of 2 things is probably going on. One, the field is either required on both, or not at all and the use case is incorrect. Or, the property belongs to a different entity. But for arguments sake, let’s say you have a property of an entity that is required sometimes and sometimes it is not. Well if you’ve managed to spread you code across controllers, and managers, and data models, and even into the view, then how will your code support a system interface instead of a user interface? And, when the different sets of code required to deal with the sometimes, some not requirement it’s very likely that you will need to persist evidence of where the field came from so that the data store and other parts of the application that use the data know which of the views allowed it or didn’t in order to instantiate an object in the model appropriately from that state.

    If all this sounds overly complex, it’s because it is. The tendency to take these wonderful tools from Microsoft, that are intended to make our jobs easier and our products cheaper, in an unguided direction that results in over-architected solutions that become brittle from lack of proper design happens all to often. This is precisely why I urge caution, and request that Microsoft is very careful about introducing this technology to the community.

    Thanks Jeff for posting a response. It provided the opportunity to elaborate more on the problems of unguided technology introduction.

  • If I want pass lots of data in different data structs from a action to a view,how should I do width this?

  • Can it run on vs2005 / .net framework 2.0 without any iis mapping settings ?

  • Hi Scott,

    I am completely new with MVC, i want to try it but i cannot find "ASP.NET MVC Web Application" in my Visual Studio 2008 beta 2. Could you tell me where can i find it?

    Thank

  • Scott,

    I have been reading this blogs and thanks for scratching inspit of your busy schedule.

    I am playing around orcas beta2. So is it possible for me to develop these with that. If not how can i code these MVC things.

    regards
    Lohith

  • Scott nice article. I'll hope that you post soon part II.
    I would also like to see the differences with MVP-pattern or
    the WCSF in future posts.

    Tia,

    Joey

  • Scott,

    Will MS MVC support an 'Wizard' functionality?

  • To dougramirez:

    Here Here!

  • This all seems nice for certain types of applications, like ones in your example that allow you to do basic views (like a basic company website that lists products). I still don't understand how you could build a very complex page using this framework. One of the "workhorse" pages in my application has multiple grids, many different webcontrols, and very complex business logic, as well as uses AJAX (Telerik's) in order to speed things up a bit. This seems like quite a departure from how most applications are built today. I doubt my company would ever use this for the business applications we do. Maybe I just don't "get it" yet though, so I'm trying to keep an open mind.

  • Scott,

    I would like to know more details of MVC pattern implementation in ASP.NET 2.0. I would like to know about page class reference to view folder. ASP.NET compiles each folder in separate assembly and give random assembly names. simply, can you put some light on page class reference to other .net folders?

  • Hi Scott,
    Great article, this is the most user-friendly explanation of MVC that I've seen.

    Most of my projects in the past have required grids (DataGrid, GridView, etc.) that must be formatted dynamically based on the data in a certain row/column. For instance, highlighting a row where the cost column is less than $100.00. Usually this is handled in the RowDataBound or RowCreated method in the page's code behind. How would you handle this scenario using the MVC framework?

    Apologies if you've already addressed this above - there's a lot of posts here!

  • Hi Scott,

    Great post the MVC framework defiantly looks like something we will use. We've been looking at Project Astoria as well and i was wondering how you would see them complementing each other or if they are competing technologies?

    Thanks for the post
    Andy

  • I think inclusion of MVC Project Template in .NET will give a good choice to developers of CakePHP. As many developers are using CakePHP to implement MVC in PHP and the MVC is becoming more and more popular to for web based application development. This post is really providing a good insight to implement MVC Project Template. I am looking forward to use it with VS 2008.

    Thank You Scott.

  • Scott,

    Thanks for the great article. I've been waiting for this by the sidelines and this maybe the Christmas gift I've been waiting for. I've dived into RoR and just love the simplicity and development architecture, however at times miss the power available from .NET framework so I'm excited about the direction ASP.NET is taking. CSS friendly adapters are no longer cutting it. I want full control. Anyhow from what

    Looks like based on the discussions here, validation and model security is placed into the hands of the controller? This seems counter to MVC. RoR provided deep emphasis in placing validation and security to the model code. ActiveRecord handles model integrity. How does ASP.NET MVC handle this? Does the default model handle this? What are your recommendations?

    I agree with DougRamirez "Data validation and security absolutely do not belong in the controller!" Validation in the controller kinda of makes all this MVC hype mute.

  • Thank you for your acticle!I'm looking for the next.That's very cool

  • Hi Scott !
    This is great article, thank so much but i have some questions about your ideas that you explained above, first that is does this method can only develop on VS 2008? and second that is can you tell me about extendable of this MVC framework?

    Finally, thanks

    Phan Huy Viet

  • Scott,

    Happy Thanksgiving ! Can't add much more to whats already been said.

    I admire your enthusiasm and passion towards your work.



  • Any word on release date... Scott.. Looking forward to try it

  • Thanks for the post, I don't like the way you have to give the view name as a string. Couldn't this be implemented using an enum instead

  • Hi Scott,

    I saw this :

    " >>>>>>> Should we expect any difference in performnace between MVC and WebForms model?
    No - in general you'll find both about the same in terms of performance. "

    And I wondered how come MVC - with the omission of viewstate injection and then parsing it again in every postback and rebuilding the object model again with that parsed data, to start with! - couldn't beat WebForms in performance?

    Thnx

  • Hi RoGer,

    >>>>>>>> Thanks for the post, I don't like the way you have to give the view name as a string. Couldn't this be implemented using an enum instead

    Yes - if you wanted to you could store the view name as an enum.

    Thanks,

    Scott

  • Hi Bob,

    >>>>>>> Any word on release date... Scott.. Looking forward to try it

    We should have the first public preview build available for download within the next two weeks.

    Thanks,

    Scott

  • Hi Scott
    Nicely explained article on ASP.Net MVC framework.
    Can you give a comparison between MVC and MVP with respect to ASP.Net. And which is a better option in what type of situation.

  • Hello Scott,

    Thanks for your blog. This is something everyone is waiting for.

    Is'nt the MVC framework, infact the Controller, implementation of the Front Controller pattern?

  • Hi Mahi,

    >>>>>> Is'nt the MVC framework, infact the Controller, implementation of the Front Controller pattern?

    Yes - the ASP.NET MVC framework uses a front-controller pattern.

    Thanks,

    Scott

  • hi scott!!!
    thanks for this indeed helpful post

  • Hi Scott

    I'm busy designing (functionality) a system to be built in .NET and we are going to begin construction in mid-January 2008. I'm very interested in using VS2008 and the ASP.NET MVC framework, possibly using SubSonic as well. Will the framework be ready for production use by then? (I see you mentioned that a public preview build will be available in two weeks) The reason I ask is that the system design will change depending on the framework that we go for.

  • Hi scott,

    I have been using the MVC in windows mobile development base on Microsoft Compact Software Factory p&p. I found dependency injection and event broker.
    Will the framework have this features?

    I learned the WCSF p&p. It is similiar with MCSF.
    So...what's the comparison between WCSP p&p and ASP.NET Framework MVC?




  • This looks pretty interesting, I was just reading about NVelocity and MonoRail.

  • This is very similar to a project on Codeplex called ProMesh, except Promesh stays away from any microsoft controls.

  • I know this may be a little bit to in-depth for the state of the MVC Framework at the moment but...
    Does the MVC framework somehow expose the controller, action & parameters sub-strings in any way? If so, when in the HttpApplication event cycle is the determination of controller / action / parameters done? If this happens before HttpApplication.AuthroizeRequest, it opens up some really nice authorization possiblities which I've had to kind of shoehorn into the system in the past.

  • Phil Haack just did a talk tonight on this topic at the LA .NET Usergroup and he was great! Very cool stuff. Can we see some posts on how migration can (eventually) be done from webforms? I know it's such a different model but this will be one of the big keys for many ASP.NET devs to get their head around. No more webform, postback, viewstate, etc.
    Thanks.

  • Could you please post the source for this project? Even if it's beta, it will be easier to learn from it now than to get the CTP later on.

  • Well, is microsoft trying to follow/copy Java/Strutus in creating apps using MVC? geez!

  • Scott,

    Thanks for the excellent blogs on this new framework, really lapping it up here. BUT, can you tell me how and where you have defined the TestViewEngine, as i cannot find it anywhere. IViewFactory I can find obviously but as for the actual class, I think you have omitted a piece on its location, design or implmentation.

    Kind Regards,

    Andrew Rea

  • Firstly, your articles are fantastic and a credit to you.

    I guess the HTTP routing feature be used on its own as a "poor mans" alternative to Web Services? For example, a web client using XMLHttpRequest needing to obtain some data from the web server in JSON format?

    I therefore presume that the View is not necessarily limited to returning only HTML - it could theoretically return any Mime type (for example, an image of a product via a URL such as "/Products/Image/55")?

    Have any performance tests been done to compare the overhead of processing requests via the MVC HTTP routing mechanism compared to direct invocation of a web-forms .aspx page? Does the fact that the controller invokes/calls the view mean the actual "view" .aspx page (the physical file) is loaded, or is this simply an in-memory invocation through the compiled assembly? Can the .aspx files of the view still be modified "on the fly" without recompiling?

    Finally, if Silverlight was going to be used for a data-centric application, does MVC benefit that in any manner compared to using a SOAP/WSDL declared Web Service (or any other technique you care to mention)?

  • Hi Scott,

    That's great stuff. I've been looking to implement something like this. Someone showed me an MVC implementation using HttpHandlers as the controllers (or access to the controller classes) but this is a much neater and cleaner model. I look forward to working with.

  • Hey Scott,

    Great work. Is there a chance you could post the unit test code shown in this post?

    Thanks!
    Michael

  • When I read your blogs with code samples, I try to follow along by building them.

    When I do this with the Categories.aspx page, I have a couple of interesting issues.

    First, the Html.ActionLink reference give me the following error when I access the page:

    CSW1502: The best overloaded method match for 'System.Web.Mvc.HtmlHelper.ActionLink(string,string)' has some invalid arguments.

    If I cast the first argument as a string, no problem.

    Second, inside the code beside (Categories.aspx.cs), in the Page_Load event, I can't get it to recognize the existence of the categoryList control. I get the blue underline, compile error of 'The name 'categoryList' does not exist int the current context'.

    I'm using the CTP release. Any thoughts?

    GregM

  • Scott:

    For Views, you mentioned two approaches to creating Views. Is one preferable to the other, for a brand-new (no legacy) application?

    Thanks,

    Aneesh Shrikhande

  • Nice of you to join us.

  • I have the same problem as GregM above. I get the message: 'The name 'categoryList' does not exist in the current context' when I try to reference the ListView in code-behind. Ideas?

    /BK

  • Greg McCarty,
    I had same problems.
    Casting to string is somewhat strange, because Eval already returns that type. It helped, however.
    Your second problem can be worked-around quite easy: just declare that control in your code behind.
    This is because for some reason (any idea why?) MVC Views don't have designer generated code which contains such declarations.

  • Hi Scott,

    Thank you very much for the detailed explanation on MVC, MVC internals and its working flow. I could able to successfully complete all the approaches that you have mentioned above, except the last approach "Rendering Approach 2: Using Server Side Controls". When I tried to run with the inline statement as mentioned in the "Rendering Approach 2: Using Server Side Controls" I got a compiler error message "The best overloaded method match for 'System.Web.Mvc.HtmlHelper.ActionLink(string, string)' has some invalid arguments" so to fix this I have converted the first eval into a string such as:
    but after this I found that all the category URL's are pointing to the same URL (/products/List) so I had to change the "category" to "Id" in the second argument(values) to get the correct category URL.

    Happy Holidays!

    PM


  • Hi Scott!

    Thanks for this great sample! I try to follow it, but ran into a minor problem (besides the already mentioned .ToString-issue..)
    The "Categories" action uses Html.ActionLink to produce the correct action links. The problem is with "Grains/Cereals" and "Meat/Poultry", where the slash obviously should not be processed by the routing-engine... if i follow the link to "Products/List/Meat/Poultry" it resuls in an error.

    What can be done about this?

    Kind regards,
    Wolfgang

  • You did a better job of explaining MVC then "the other guy". I missed the link between the database model and the Data Context class. Is the assumption that if the name of my database model is Northwind.dbml then the Data Context class will be NorthwindDataContext.cs? Or is there preprocessor somewhere that makes that link?
    TIA

  • Very nice article. Informative, objective, and very much direct to the point.

  • This framework will surely be very useful to all of us!

Comments have been disabled for this content.