ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

The last few weeks I have been working on a series of blog posts that cover the new ASP.NET MVC Framework we are working on.  The ASP.NET MVC Framework is an optional approach you can use to structure your ASP.NET web applications to have a clear separation of concerns, and make it easier to unit test your code and support a TDD workflow.

The first post in this series built a simple e-commerce product listing/browsing site.  It covered the high-level concepts behind MVC, and demonstrated how to create a new ASP.NET MVC project from scratch to implement and test this e-commerce product listing functionality.  The second post in this series drilled deep into the URL routing architecture of the ASP.NET MVC framework, and discussed both how it worked as well as how you can handle more advanced URL routing scenarios with it.

In today's blog post I'm going to discuss how Controllers interact with Views, and specifically cover ways you can pass data from a Controller to a View in order to render a response back to a client.

Quick Recap from Part 1

In Part 1 of this series, we created an e-commerce site that implemented basic product listing/browsing support.  We implemented this site using the ASP.NET MVC Framework, which led us to naturally structure the code into distinct controller, model and view components.

When a browser sends a HTTP request to our web site, the ASP.NET MVC Framework will use its URL routing engine to map the incoming request to an action method on a controller class to process it.  Controllers in a MVC based application are responsible for processing incoming requests, handling user input and interactions, and executing application logic based on them (retrieving and updating model data stored in a database, etc).

When it comes time to render an HTML response back to the client, controllers typically work with "view" components - which are implemented as separate classes/templates from the controllers, and are intended to be focused entirely on encapsulating presentation logic. 

Views should not contain any application logic or database retrieval code, instead all application/data logic should only be handled by the controller class.  The motivation behind this partitioning is to help enforce a clear separation of your application/data logic from your UI generation code.  This makes it easier to unit test your application/data logic in isolation from your UI rendering logic.

Views should only render their output using the view-specific data passed to it by the Controller class.  In the ASP.NET MVC Framework we call this view-specific data "ViewData".  The rest of this blog post is going to cover some of the different approaches you can use to pass this "ViewData" from the Controller to the View to render.

A Simple Product Listing Scenario

To help illustrate some of the techniques we can use to pass ViewData from a Controller to a View, let's build a simple product listing page:

We will use a CategoryID integer to filter the products that we want to display for the page.  Notice above how we are embedding the CategoryID as part of the URL (for example: /Products/Category/2 or /Products/Category/4).

Our product listing page is then rendering two separate dynamic content elements. The first is the textual name of the category we are displaying (for example: "Condiments").  The second is an HTML <ul><li/></ul> list of product names.  I've circled both of these in red in the above screen-shot.

Below we'll look at two different approaches we can use to implement a "ProductsController" class that processes the incoming request, retrieves the data necessary to handle it, and then passes this data to a "List" view to render it.  The first approach we'll examine passes the data using a late-bound dictionary object.  The second approach we'll examine passes it using a strongly-typed class.

Approach 1: Passing ViewData using the Controller.ViewData Dictionary

The Controller base class has a "ViewData" dictionary property that can be used to populate data that you want to pass to a View.  You add objects into the ViewData dictionary using a key/value pattern.

Below is a ProductsController class with a "Category" action method that implements our product listing scenario above.  Notice how it is using the category's ID parameter to lookup the textual name of the category, as well as retrieve a list of the Products within that category.  It is storing both of these in the Controller.ViewData collection using a "CategoryName" and "Products" key:

 

Our Category action above is then calling RenderView("List") to indicate which view template it wants to render.  When you call RenderView like this it will pass the ViewData dictionary to the View in order for it to render.

Implementing Our View

We will implement our List view using a List.aspx file that lives under the \Views\Products directory of our project.  This List.aspx page will inherit the layout of the Site.Master MasterPage under the \Views\Shared folder (right click within VS 2008 and select Add New Item->MVC View Content Page to wire up a master page when you create a new view page):

When we create our List.aspx page using the MVC View Content Page template it derives not from the usual System.Web.UI.Page class, but rather from the System.Web.Mvc.ViewPage base class (which is a subclass of the existing Page class):

The ViewPage base class provides us with a ViewData dictionary property that we can use within the view page to access the data objects that were added by the Controller.  We can then take these data objects and use them to render HTML output using either server controls, or by using <%= %> rendering code.

Implementing Our View Using Server Controls

Below is an example of how we could use the existing <asp:literal> and <asp:repeater> server controls to implement our HTML UI:

We can bind the ViewData to these controls using the below code-behind class (note how we are using the ViewPage's ViewData dictionary to-do this):

Note: Because we have no <form runat="server"> on the page, no view-state is ever emitted.  The above controls also don't automatically render any ID value - which means that you have total control over the HTML emitted.

Implementing our View using <%= %> Code

If you prefer to use inline rendering code to generate the output, you can accomplish the same result as above using the List.aspx below:

Note: Because ViewData is typed as a dictionary containing "objects", we need to cast ViewData["Products"] to a List<Product> or an IEnumerable<Product> in order to use the foreach statement on it.  I am importing both the System.Collections.Generic and MyStore.Models namespaces on the page to avoid having to fully qualify the List<T> and Product types.

Note: The use of the "var" keyword above is an example of using the new C# and VB "type inference" feature in VS 2008 (read here for my previous post on this).  Because we have cast ViewData["Products"] as a List<Product> we get full intellisense on the product variable within the List.aspx file:

Approach 2: Passing ViewData using Strongly Typed Classes

In addition to supporting a late-bound dictionary approach, the ASP.NET MVC Framework also enables you to pass strongly typed ViewData objects from your Controller to your View.  There are a couple of benefits of using this strongly typed approach:

  1. You avoid using strings to lookup objects, and get compile-time checking of both your Controller and View code
  2. You avoid the need to explicitly cast values from the ViewData object dictionary when using strongly-typed languages like C#
  3. You get automatic code intellisense against your ViewData object within both the markup and code-behind of your view page
  4. You can use code refactoring tools to help automate changes across your app and unit-test code base

Below is a strongly typed "ProductsListViewData" class that encapsulates the data needed for the List.aspx view to render our product listing.  It has CategoryName and Products properties (implemented using the new C# automatic properties support):

We can then update our ProductsController implementation to use this object to pass a strongly typed ViewData object to our view:

Notice above how we are passing our strongly typed ProductsListViewData object to the View by adding it as an extra parameter to the RenderView() method.

Using the View's ViewData Dictionary with a Strongly Typed ViewData Object

The previous List.aspx view implementations we wrote will continue to work with our updated ProductsController - no code changes required.  This is because when a strongly typed ViewData object is passed to a View that derives from ViewPage, the ViewData dictionary will automatically use reflection against the properties of the strongly typed object to lookup values.  So code in our view like below:

will automatically use reflection to retrieve the value from the CategoryName property of the strongly typed ProductsListViewData object we passed when calling the RenderView method.

Using the ViewPage<T> Base Class to Strongly Type ViewData

In addition to supporting a dictionary based ViewPage base class, the ASP.NET MVC Framework also ships with a generics based ViewPage<T> implementation.  If your View derives from ViewPage<T> - where T indicates the type of the ViewData class the Controller passes to the view - then the ViewData property will be strongly typed using this class type.

For example, we could update our List.aspx.cs code-behind class to derive not from ViewPage, but from ViewPage<ProductsListViewData>:

When we do this, the ViewData property on the page will change from being a dictionary to being of type ProductsListViewData.  This means that instead of using string-based dictionary lookups to retrieve data, we can now use strongly typed properties:

We can then use either a sever-control approach, or a <%= %> rendering approach to render HTML based on this ViewData.

Implementing Our ViewPage<T> Implementation Using Server Controls

Below is an example of how we could use the <asp:literal> and <asp:repeater> server controls to implement our HTML UI.  This is the exact same markup that we used when our List.aspx page derived from ViewPage:

Below is what the code-behind now looks like.  Note how because we are deriving from ViewPage<ProductsListViewData> we can access the properties directly - and we don't need to cast anything (we'll also get refactoring tool support anytime we decide to rename one of the properties):

Implementing our ViewPage<T> implementation using <%= %> Code

If you prefer to use inline rendering code to generate the output, you can accomplish the same result as above using the List.aspx below:

Using the ViewPage<T> approach we now no longer need to use string lookups of the ViewData.  Even more importantly, notice above how we no longer need to cast any of the properties - since they are strongly typed.  This means we can write foreach (var product in ViewData.Products) and not have to cast Products.  We also get full intellisense on the product variable within the loop:

Summary

Hopefully the above post helps provide some more details about how Controllers pass data to a View in order to render a response to a client.  You can use either a late-bound dictionary, or a strongly-typed approach to accomplish this.

The first time you try and build an MVC application you will likely find the concept of splitting up and separating your application controller logic from your UI generation code a little strange.  It will probably take some dedicated app-building time before you become comfortable and orient your mind-set around the idea of processing a request, executing all of the application logic for it, packaging up the viewdata required to build a UI response, and then handing it off to a separate view page to render it.  Important: If this model doesn't feel comfortable to you then don't use it - the MVC approach is purely optional, and we don't think it is something everyone will want to use. 

The benefit and goal behind this application partitioning, though, is that it enables you to run and test your application and data logic in isolation from your UI rendering code.  This makes it much easier to develop comprehensive unit tests for your application, as well as to use a TDD (test driven development) workflow as you build your applications.  In later blog posts I'll drill in deeper into this more, as well as discuss best practices you can use to easily test your code.

Hope this helps,

Scott

Published Thursday, December 06, 2007 2:49 AM by ScottGu
Filed under: , ,

Comments

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 6:10 AM by zYm3N Bogusław Faja

Scott: How much time do we have to first CTP? :-)

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 6:27 AM by Christian

Sorry for being off-topic but could you tell me if the .Net base library source code will be released this week? I just can't await it!

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 6:27 AM by John R.

Hello Scott,

do you know if there will be a Go Live License for the MVC Framework, that you will release this week? Can we build a commercial application based on it?

Thank you

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 6:52 AM by danieb

Great, when can we have it! Also could you explain how the update actions work in the controllers? The and perhaps explain how the "UpdateFrom()" works.

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 6:53 AM by Dove

Thanks

Expectative

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 6:59 AM by Ben

Typed viewdata is definitely nice, especially with intellisense in the view - something sorely lacking in Monorail IMO.

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 7:04 AM by James Steele

I love drinking from the fire hose that is ScottGu! Great post Scott. Rob Conery just put out another related post: "ASP.NET MVC Preview: Using The MVC UI Helpers"

blog.wekeroad.com/.../aspnet-mvc-preview-using-the-mvc-ui-helpers

Scott what product do you use for doing your screen shots?

James

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 7:04 AM by Fisher Ning

Great, Can we download it tomorrow?

# ASP.NET MVC (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 7:15 AM by DotNetKicks.com

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 7:18 AM by Maciej Kuczara (ABB)

Great article, i have strong Java background so passing data through layers to view isnt anything i could be afraid of :)

One question Scott: Let say i'm jumpng on MS MVC bandwagon, do i have to abandon asp.net Page Life cyclce godddies, should i set up my mind to different approach.

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 7:23 AM by onovotny

Scott, can you go into some detail about how ASP.Net's page / user control caching works with the MVC Framework?  With "traditional" ASP.Net, since the page handles the request, it can bypass any rendering logic if needed.  It's also very easy to declare parameters to the page caching.  In MVC, do the controllers have a way of declaring a cache; if not, how does it work?

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 7:31 AM by Muhammed Tahiroglu

It's very nice feature that the ViewPage supports strongly typed ViewData.

My question is:

Some asp.net controls require <form runat=server>. If we use a asp:dropdownlist for example, we have to place in the asp:form. And this means viewstate comes back! Is there any way to get rid of hidden form fields? Or you suggest that we do must use classic HTML controls?

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 7:32 AM by Fardin

Hi Scott

It would be nice if you can just compare a bit our MVC with ROR.

Within ROR, we can create tables, Columns and Rows with Ruby, without using a single line of SQL, and all its done through ActiveRecord.

In short all CRUD advantages.

SubSonic is almost in this line. Can you explain more in this line or how SubSonic can be used to take ActiveRecord Type advantages.

I know, you are flooded with requests, but this is perhaps every one would like to know.

Thanks

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 7:33 AM by Igor

Hi Scott!

I suppose that I am not first ask this question, but when do you expect to deliver any version of the framework?

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 7:36 AM by PK

Hi Scott,

In the last example you made a ProductsListViewData class which you then passed in to the RenderView(..) method as the second argument. Instead of making a seperate class (and .cs file) for the ProductsListViewData, can you do an anonymous type instead ?

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 7:38 AM by Kigorw

Hi Scott,

Can I use HttpContext.Current.Items to share values instead of ViewData ?

Igor

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 7:49 AM by Max

The strongly typed ViewData and generic ViewPage<T> combination is billiant! The more I read about ASP.NET MVC the more excited I get. Can't wait to get my hands on it in a few days! Thanks for anothe great post!

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 8:26 AM by Scott S.

Hi Scott.  Been anxiously reading all of your posts and it really looks like you've nailed the MVC implementation.  The ASP.NET team has been doing some incredible work lately.  Will the ASP.NET 3.5 Extensions public preview coming this week include any type of Go Live license? (especially for the MVC bits)

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 8:46 AM by PBZ

Any reason why RenderView takes a string? Do you plan on having some kind of proxy, like we have with the controls on a aspx page in the .designer file, so that we could have intellisense for the available views? And how does it know where to find that "List" view at runtime? (which folder ie) What if I have more than one "List" views under different folders/namespaces?

Thanks.

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 8:55 AM by Erick

It's a great Framework!

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 8:57 AM by Peter

As someone relatively new to ASP.NET, coming from other web languages, this looks so awesome to me. It's so much more like web development (at least what I'm used to) than the Web Forms model. I no longer feel like I'm losing something by switching to ASP.NET. Can't wait to get my hands on it!

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 8:58 AM by Chad Gross

Scott,

Is the roadmap still accurate and we should see a release of the MVC and Entity Framework this week yet?  Thanks.

Chad

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 8:59 AM by Legowo Budianto

Superb, ...but I still longing for the IOC integration (Spring.NET, Windsor, StructureMap)...maybe in the next post?

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 9:03 AM by Konstantin

Hi Scott,

what if there's a need to render multiple ViewData objects (like ProductsListViewData) with the generic approach? (ViewPage<ProductsListViewData>)

Greerings

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 9:08 AM by Rob Bazinet

Scott,

Great post as were Part 1 & 2.  I really like what I see here, as a .NET and Rails developer it's nice to see how the two world seem to be coming together for me.  I am huge MVC fan, primarily with my work with Rails.  I think this will make the ASP.NET developer or architect to truly create an extensible and testable system in .NET so much easier.

-Rob

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 9:10 AM by Andre

anything you can do to avoid the { and } symbols in loops in the view? looks ugly and potentially confusing too...i would prefer something like the if-endif/foreach-endforeach approach in PHP

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 9:26 AM by Paul

Thanks for the great MVC posts. I have a request for a post on how security is going to work.  Security is a major part of web apps and I don't see how it is going to work in MVC.  Fredrik has a post about this using PrincipalPermission.  However throwing exceptions doesn't seem to be the right solution.  We should be able to use the <location> element as always and have it redirect to the login page.  Otherwise, we could config permission in the route information too.  Just so there is something built in to handle security and redirecting to a login.  I can understand that maybe this isn't in the cpt yet but at least let us know what direction the mvc frameworks is going to go in this area.  

Thanks,

~ Paul

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 9:31 AM by Dennie

Hi Scott,

Can we still do two-way property binding with server controls, so that when a form is POST'ed an updated ViewData is provided to the controller (and as a result, it is possible to save the data changes).

Tnx,

Dennie

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 9:39 AM by Luc R

Hi Scott,

This looks impressive and very powerful.

Modern websites are build with Modules based Content Management Systems like dotnetnuke. Have looked at this? And can you give us a glimpse how MVC will fit in this kind of websites. How should we construct a controller to support a page with several controls on one page, all with its own functionality like data entry?

Best regards,

Luc

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 9:45 AM by Scott McCormick

I love where all this is headed but am curious if you would comment on one thing. I presently share the business logic and data layers between multiple apps (web and form).  Is there a plan to free up the View part of this framework so that it's not soley asp.net based?

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 9:56 AM by The Other Steve

Where can we download MVC?

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 9:56 AM by TeckChavez

Great series so far.  Hopefully part 4 will be around how to get data from the user passed into the controller (unless it is easy enough to just answer in the comments section).  I understand and like this approach for browsing and displaying information from a few inputs, but I am not able to get my head around saving form data entered by the user using this approach.

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 10:14 AM by Carlos Lone

Great Post !!!!,  I would like to know where can I download the MVC framework?,

Regards,

# ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views - ScottGu&rsquo;s Blog &raquo; article &raquo; Thats The New Thing!

Pingback from  ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views - ScottGu&rsquo;s Blog &raquo; article &raquo; Thats The New Thing!

# 11 Links Today (2007-12-06)

Thursday, December 06, 2007 10:18 AM by 11 Links Today (2007-12-06)

Pingback from  11 Links Today (2007-12-06)

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 10:22 AM by Jack

I'm still interested in what plans or ideas are out there for subcontrollers/web parts and other embedded "classic model" functionality.  I feed the availability of ways to support this could make or break decisions to implement with MVC.

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 10:28 AM by Rodrigo

Scott when this baby will be avaiable?

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 10:32 AM by Murtaza Rizvi

Nice series, eagerly waiting to see AJAX approach in the new ASP.NET MVC Framework, so when shall we expext that.

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 10:48 AM by MN

When I see that codes I see Tapestry Framework. http://tapestry.apache.org/

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 10:54 AM by evan closson

It all looks great and I can't wait to use it.  I just hope Microsoft gives a nod in the direction of RoR and Monorail for laying the foundations the ASP.Net MVC Framework is building upon.  Great work! I just don't want Microsoft to get all the credit for the advances the community at large has brought about.

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 10:59 AM by David Fauber

Thanks for this posting.  One thing that I'm still trying to get my head around is that Presentation from Model is the primary concern this is supposed to address, but it seems all the focus is on separating view and controller.

This leaves the same asp-ish feeling code/markup combo in the View, which seems to be a clear mixing of presentation and model to me.

In trying to tackle this on my own using the webforms paradigm, I created User Controls to represent Spreadsheet, Grid, and Detail views.  The model consisted of a datasource that could return a datatable and configurable properties on the controls to set up columns and other display properties.  Init handled asynch partial page requests and shortcircuited the rest of the page lifecycle in attempt to be REST-ish.

I had been trying to set this up in such a way that it would be an easy port to the MVC framework when it came out, but now I'm starting to think my thinking is not as in-line with this framework as I'd originally thought.

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 11:18 AM by James

This is coming together nicely. I was just hoping you might explain why there are 3 different ways to pass the ViewData? Does each method offer something that the others don't? If not, surely it would be best to choose one method and force all developers to follow the same practice?

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 11:18 AM by Esbe

Great post as always !

I'm wondering how user control's data will be passed to views... Will the controller need to build all the required information for the view (for example if the view contains a sitemap or login status, will we need to also pass that information in the ViewData) ? Or will there be some kind of viewcomponent in the MVC Tookit that we will be able to embed into the view (which in itself will start a new controller-view cycle) ?

Your examples are kept simple, but I'm having a hard time seeing how complex pages that contain many parts will be built.

Anxious to play with the upcoming bits...

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 11:22 AM by Richard

This looks like a nice and clean approach to developing the presentation tier.

Do you have any idea what how this compares to Web Forms in terms of performance?

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 11:28 AM by JMac

Still looking for the MVC Framework.  Do you have any kind of release we can play with?

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 11:35 AM by Sean Feldman

Thank you for updates about MVC framework. Will you expand a bit about how to submit data with this framework? Also will the ViewPage have all those events that a normal Page had - what for?

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 11:38 AM by Rob Ellis

Ditto to TeckChavez #6 comment.  Thanks for the all the work on this Scott

# The Daily Find #12 - TechToolBlog

Thursday, December 06, 2007 11:41 AM by The Daily Find #12 - TechToolBlog

Pingback from  The Daily Find #12 - TechToolBlog

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 11:43 AM by ScottGu

Hi Christian,

>>>>>>> Sorry for being off-topic but could you tell me if the .Net base library source code will be released this week? I just can't await it!

Unfortunately it won't be this week - but we are pretty close.  We are just doing final testing now.

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 11:43 AM by ScottGu

Hi John,

>>>>>> do you know if there will be a Go Live License for the MVC Framework, that you will release this week? Can we build a commercial application based on it?

There isn't a formal go-live license, but there also isn't any license that prevents you from building apps and going live with them.  So you could start to build commercial applications with it.

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 11:44 AM by ScottGu

Hi Danieb,

>>>>>> Great, when can we have it! Also could you explain how the update actions work in the controllers? The and perhaps explain how the "UpdateFrom()" works.

That is going to be the focus of my text tutorial in this series.  Specifically I'll be covering how you handle form posts, map input to objects, and use the new Html UI helpers to help generate output.

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 11:48 AM by Remy

Really like the idea of MVC, but my app is heavily built on individual controls that are assembled on different pages, which makes it really flexible and increases the usability. This MVC approach seems to kinda prevent this, no? Or how would you go about solving this issue? Example: I have a Tag cloud that is on the customer, company and task page. Now sure how I would implement that with MVC?

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 11:50 AM by ScottGu

Hi James Steele,

>>>>>> Scott what product do you use for doing your screen shots?

I use snagit as my screen capturing software.  It dramatically simplifies grabbing snippets of the screen, and also includes built-in drawing tools to highlight things (for example with red ovals, etc).  I think it costs about $39.  I highly, highly recommend it!

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 12:05 PM by ScottGu

Hi Maciej,

>>>>>>>> One question Scott: Let say i'm jumpng on MS MVC bandwagon, do i have to abandon asp.net Page Life cyclce godddies, should i set up my mind to different approach.

When you use the ASP.NET MVC approach you'll want to have all post in your site go to your Controller.  This helps ensure that the application can be easily tested and preserves the separation of concerns.  This is different from using ASP.NET server controls which postback to themselves (which is very powerful too - but means that it can sometimes be slightly harder to test).

What doesn't change is that all of other ASP.NET pieces (forms authentication, role management, session state, caching, profiles, configuration, compilation, httprequest/response, health monitoring, etc, etc) works with both web forms based pages and MVC based pages.  MVC UI are also built with .aspx, .master, and .ascx files - so there is a high level of skill re-use there as well.

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 12:07 PM by ScottGu

Hi onovotny,

>>>>>>>> Scott, can you go into some detail about how ASP.Net's page / user control caching works with the MVC Framework?  With "traditional" ASP.Net, since the page handles the request, it can bypass any rendering logic if needed.  It's also very easy to declare parameters to the page caching.  In MVC, do the controllers have a way of declaring a cache; if not, how does it work?

Yes - Controllers can also declare cache settings.  For the first preview you would use the Response.Cache API to-do this (you then have complete control over the settings used).  For the next preview we are also planning on support a declarative attribute-based way that you can set outcache settings (by adding an attribute to your controller or action method).

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 12:08 PM by ScottGu

Hi Muhammed,

>>>>>>>> Some asp.net controls require <form runat=server>. If we use a asp:dropdownlist for example, we have to place in the asp:form. And this means viewstate comes back! Is there any way to get rid of hidden form fields? Or you suggest that we do must use classic HTML controls?

I'll cover this more in my next blog in this series.  We have helpers that can automate generating things like dropdownlists, etc.  Think of them as controls for MVC.  These don't use viewstate and give you a little more control over the output of your HTML.

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 12:23 PM by ScottGu

Hi Fardin,

>>>>>> It would be nice if you can just compare a bit our MVC with ROR.  Within ROR, we can create tables, Columns and Rows with Ruby, without using a single line of SQL, and all its done through ActiveRecord.  In short all CRUD advantages.

>>>>>> SubSonic is almost in this line. Can you explain more in this line or how SubSonic can be used to take ActiveRecord Type advantages.

RoR is made up of several components.  "Action Controller" is the name of the MVC framework that Rails uses.  That is the closest analogy to the ASP.NET MVC Framework - and at a high-level the ASP.NET MVC framework uses many of the same core concepts (URLs map to controller actions).  The ASP.NET MVC Framework has a few additional features (like the ability to map incoming parameters dirctly to action method parameters).  It is also more explicit about calling RenderView within the request.  

"Active View" is the name of the View engine that Rails uses.  This is analagous to the .aspx/.master/.ascx infrastructure ASP.NET has.  Our view engine is IMO a little richer, and supports several additional features (declarative controls/components, templating, multiple regions for nested master pages, WYSIWYG designer, strongly typed ViewData access, pluggable storage provider, declarative localization, etc).

"Active Record" is the name of the ORM (object relational mapper) that RoR uses.  This is analagous to an ORM in the .NET world - whether it is LINQ to SQL, LINQ to Entities, LLBLGen, SubSonic, NHibernate, ActiveRecord (the .NET version), etc.  All of these ORMs have ways to map rows and columns in a database to objects that a developer then manipulates and works against (and can save changes back).  The LINQ to SQL ORM is built-in to .NET 3.5 today, and LINQ to Entities will be built-in with .NET 3.5 SP1.

I think from your follow-up question above you are referring specifically to the "migrations" feature in RoR - which allows you to define table schemas using code, and version the schemas forward/backward.  There isn't a built-in version of this in the core .NET Framework today - although the SubSonic project has recently released a version that allows you to-do this using .NET.  You can find out more about it here: www.subsonicproject.com

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 12:25 PM by ScottGu

Hi PK,

>>>>>>> In the last example you made a ProductsListViewData class which you then passed in to the RenderView(..) method as the second argument. Instead of making a seperate class (and .cs file) for the ProductsListViewData, can you do an anonymous type instead ?

You can definitely pass an anonymous type in place of a strongly typed one to RenderView.  However, because anonymous types are "anonymous" you can't use ViewPage<T> on the view side in order to get strong typing and intellisense against it.  You can, though use ViewPage and use the dictionary API against it.

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 12:29 PM by ScottGu

Hi Kigorw,

>>>>>> Can I use HttpContext.Current.Items to share values instead of ViewData ?

You can technically do this, although in general we recommend against it.  The reason is that it makes testing harder for the application.  The better approach is to pass the viewdata either using the Controller.ViewData dictionary or as a parameter argument to RenderView().

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 12:34 PM by ScottGu

Hi Legowo,

>>>>>> Superb, ...but I still longing for the IOC integration (Spring.NET, Windsor, StructureMap)...maybe in the next post?

I am planning on posting about IOC and dependency injection in the future (the ASP.NET MVC framework fully supports it and can be used with Spring.NET, Windsor, StructureMap, etc).  I have a few other more basic MVC tutorials I need to get out of the way first - but testing and dependency injection are on the list for the future.

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 12:35 PM by ScottGu

Hi PBZ,

>>>>>>>>> Any reason why RenderView takes a string? Do you plan on having some kind of proxy, like we have with the controls on a aspx page in the .designer file, so that we could have intellisense for the available views? And how does it know where to find that "List" view at runtime? (which folder ie) What if I have more than one "List" views under different folders/namespaces?

The folder path information is part of the default view resolution engine.  This is pluggable - so if you want to change the semantics you can. You could also come up with a mechanism to strongly typed the view names.

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 12:38 PM by ScottGu

Hi Konstantin,

>>>>>>> what if there's a need to render multiple ViewData objects (like ProductsListViewData) with the generic approach? (ViewPage<ProductsListViewData>)

The recommended guidance would be to have your ProductsListViewData object have multiple sub-properties.  That way you don't need multiple ViewData objects - instead you just reference the properties via it:

ViewData.CategoryName

ViewData.Products

ViewData.Suppliers

ViewData.Products[0].ProductName

etc.

Hope this helps,

Scott

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 12:39 PM by ScottGu

Hi Andre,

>>>>>>> anything you can do to avoid the { and } symbols in loops in the view? looks ugly and potentially confusing too...i would prefer something like the if-endif/foreach-endforeach approach in PHP

If you use VB for your views you'll get if/else and end instead of { }

Thanks,

Scott

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 12:52 PM by Dragan Panjkov

Hope to see this baby tomorrow! When you bring together Phil Haack, Scott Hanselman, Rob Conery on same product, I expect nothing less than excellence as final result (of course, not in CTP).

Keep up with good work!

Dragan

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 12:57 PM by Gagan Rajpal

Hi Scott,

Is it possible to use xaml for the view, will there be any guidelines for using the mvc framework with WPF and Silverlight?

Thanks,

Gagan

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 1:24 PM by Josh

Scott,

With the release of the MVC framework, will it ship w/ examples?

Also, what impact does your team see the MVC framework making on Multi-tier devleopment?

thanks!

Josh

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 1:36 PM by Ben Hayat

Hi Scott;

I like to know how MVC will affect third party data bound components, i.e. DevExpress, Infragistic or Telerik that use AJAX and postback with their data components? To use MVC at this point, are our choices limited to the MSFT components that come with ASP.Net that are MVC compatible or can we continue using our third party products?

Thanks!

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 2:13 PM by Dave

I love the strongly typed approach.  I'm really looking forward to the CTP.

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 3:04 PM by Jim

Scott,

How do you recommend passing viewdata to a master page?  I would prefer to use the inline code rendering approach. Will you need to include the viewdata in every controller action that uses a master page or can you do it once with an alternative mechanism?

Thanks,

Jim

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 3:04 PM by Damsel in distress

Hi Scott,

The patterns and practices team released the MVP block not long ago. Today I found out about Volta - http://labs.live.com/volta/.

This sums up to 6 web development platforms by Microsoft.

-ASP.NET (WebForms)

-MVC

-MVP

-SilverLight

-WPF (abap files)

-Volta (looks like some Script# derivate)

Could you please blog about all those different platforms? What are their advantages and disadvantages? When should one use one in favor of the other?

I am sure lots of people would appreciate it if you shed some light.

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 3:10 PM by Dancoe (UndocNet.BlogSpot.com)

not much different from the way i implemented on my Unofficial ASP.NET MVC framework i posted on my blog. Getting the intellisense on the page i usefull. I hope it not so buggy as it was in 2005, when you would not get the intellisense to work unless you closed the page tab and open it again.

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 3:24 PM by Rupert

I'd just like to say how pleased I am to see the leaps that Microsoft is making with it's web development technology at the moment. Speaking as someone who was on the verge of jumping ship to Ruby on Rails and taking my development team with me, I can safely say that I have seen more than enough in C# 3.0 and the MVC framework to keep me on board and to actually get me excited about using Asp.Net for the first time in quite a while. Keep up the good work!

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 3:26 PM by mkidder

Scott, Is the "ProductListViewData" class contained in the "ProductsController.cs" file, or in another file. It wasn't quite clear in the screenshots.

Can't wait to start on this....

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 4:08 PM by John Shissler

Nice implementation of a proven pattern.  It definitely has benefit in that nearly all functionality (excepting UI interaction) can be unit tested outside of IIS.  I think the key to adoption will be creating MVC AJAX extensions/toolkit that are on-par functionally with the current code-behind/page postback model.  Also, in your MVC examples, I think you should steer away from using the in-line rendering model.  It reminds me of old .ASP pages (ugh!) and it mixes presentation with too much logic -- something that you folks at MS touted as being the reason to go to code-behind pages in the first place and is not the way to allow page designers to work separately from developers on the UI.  I think anyone that would be interested in MVC would want to do it correctly and following best practices.  Don't make the examples easier just to reach a broader audience.

- John

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 4:31 PM by Rupak Ganguly

Scott, extremely good explanation of a very powerful implementation. If you keep writing like this, I guess people will GET what MS design/code is really intended for. Giving insight into what the devleopers / architects thought when designing new stuff will encourage proper use and avoid misuse. Keep it up. I am so glad you still find time to do this stuff.

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 4:41 PM by Kapil

Hi Scott,

Separation of presentation layer (view) from business(model) can also achieved if you design your application in such a manner. I believe we can test each layer separately in such a design as well. What are the other benefits of using the MVC framework?

Thanks,

Kapil

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 5:05 PM by Jeffrey Palermo

A Polymorphic Podcast just became available.  I interviewed with Craig Shoemaker about the MVC Framework.  Listen here: polymorphicpodcast.com/.../aspnetmvc

It's on polymorphicpodcast.com

# ASP.NET MVC CTP, podcast, and mvccontrib open source project - Jeffrey Palermo [MVP]

Pingback from  ASP.NET MVC CTP, podcast, and mvccontrib open source project - Jeffrey Palermo [MVP]

# re: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views

Thursday, December 06, 2007 6:04 PM by Mike

>>>>>> Our view engine is IMO a little richer, and supports several additional features (declarative controls/components, templating, multiple regions for nested master pages, WYSIWYG designer, strongly typed ViewData access, pluggable storage provider, declarative localization, etc).

This is hard to imagine, I have not seen one example yet of a declarative control in ASP.NET MVC. Also, how is templating going to work. Again, the examples just use a foreach loop. And how is the designer going to show anything that even comes close to the final view, if all dynamic stuff is done by method calls? Will it execute them in the background? Not that I care about the designer, I've not used it in 2 years of ASP.NET, but it seems that the general architecture would exclude any kind of meaningful designer as well as declarative web controls.

First thing I'll do tomorrow is try all web controls and see which can be use, I think the repeater might actually w