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 6, 2007 2:49 AM by ScottGu
Filed under: , ,

Comments

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

Thursday, December 6, 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 6, 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 6, 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 6, 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 6, 2007 6:53 AM by Dove

Thanks

Expectative

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

Thursday, December 6, 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 6, 2007 7:04 AM by Fisher Ning

Great, Can we download it tomorrow?

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

Thursday, December 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 2007 10:14 AM by Carlos Lone

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

Regards,

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

Thursday, December 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 2007 11:38 AM by Rob Ellis

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

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

Thursday, December 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 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 6, 2007 6:27 PM by ranunes

Hi Scott,

Dude how is busy here?

Tomorrow is a big day. I will change my blog to MVC Framework...

Thanks,

Roberto.

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

Thursday, December 6, 2007 7:02 PM by Steve

Looks great Scott - ship it!  :)

I like the flexibility.

I'd like to see how Ajax gets implemented with this new framework

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

Thursday, December 6, 2007 8:07 PM by Shailen Sukul

Hi Scott,

Great work by your team!

Just on the ProductsListViewData class, doesn't it have to inherit from a base class to indicate it holds viewstate data? It will work fine in the strongly typed scenario but in the the reflection based scenario, it would be good if the ASP.Net engine can at least know that the given viewstate class is a ViewState type of class.

Hope I make sense.

Thanks.

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

Thursday, December 6, 2007 9:07 PM by Lance Fisher

It feels like Christmas Eve already waiting for the CTP tomorrow!

I was wondering if it would be possible through the use of server controls or another tool to change this code:

<% foreach (var product in (ViewData["Products"] as List<Product>)) { %>

 <li>

   <%= product.ProductName %>

 </li>

<% } %>

Into something more like this:

<my:Products>

 <li>

   <my:ProductName />

 </li>

</my:Products>

Thanks,

Lance

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

Thursday, December 6, 2007 11:17 PM by ScottGu

Hi Dennie,

>>>>>>>> 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).

I'll cover how form post data is handled with the MVC framework with my next tutorial post.  Conceptually your view will post directly to an action on your Controller.  We have helpers to manage this - as well as to extract the posted values within your Controller and bind it back to your model.  Hopefully this will make more sense with my next tutorial post.

Hope this helps,

Scott

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

Thursday, December 6, 2007 11:18 PM by ScottGu

Hi Luc,

>>>>>>> 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?

I'll cover form input with my next blog tutorial post.  You should be able to build a good CMS system with the MVC framework.  

Thanks,

Scott

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

Thursday, December 6, 2007 11:20 PM by ScottGu

Hi 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?

There isn't automatic support to re-use a Controller across both a web and client front-end - although it would be possible to-do this.  When building the MVC framework we looked hard at enabling this, but ultimately concluded that doing so would require that we abstract out a lot of the web nature of the MVC framework - and perhaps make it to squishy and not as well suited for web development.  

Hope this helps,

Scott

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

Thursday, December 6, 2007 11:21 PM by ScottGu

Hi 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.

Part 4 will indeed cover how user data is passed into the controller. :-)

Thanks,

Scott

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

Thursday, December 6, 2007 11:23 PM by ScottGu

Hi 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.

The first public preview of the MVC framework doesn't have built-in support for sub-controllers.  But we are working on coming up with a good model for enabling this in a future preview.

Thanks,

Scott

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

Thursday, December 6, 2007 11:24 PM by ScottGu

Hi Murtaza,

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

We will have ASP.NET AJAX support with the ASP.NET MVC Framework.  I'll talk more about this in a future tutorial series post.

Thanks,

Scott

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

Thursday, December 6, 2007 11:28 PM by ScottGu

Hi 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?

Conceptually there are two ways to pass viewdata - either as a dictionary, or as a strongly typed object.  In general I recommend using the strongly typed dictionary approach - since this gives you better compilation checking, intellisense, and refactoring support.  There are, however, some times when having a more latebound dictionary approach ends up being flexible for more dynamic scenarios.

Hope this helps,

Scott

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

Thursday, December 6, 2007 11:30 PM by ScottGu

Hi Esbe,

>>>>>>> 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) ?

For the first preview you'd have the controller pass the viewdata for the entire request to the view page that it renders.  The view page can then in turn pass all, or a subset, of the viewdata to user controls to render.

For a later preview we are looking at ways to implement what we call "subcontrollers" that handle partial page scenarios better.  We haven't finalized the design of this yet - but that might ultimately work well for this scenario too.

Hope this helps,

Scott

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

Thursday, December 6, 2007 11:32 PM by ScottGu

Hi 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?

Performance is often hard to comment on, since it really depends on exact scenarios.  But in general I think you'll find the MVC framework really, really fast.  From a pure rendering perspective it has a slightly lighter-weight rendering model compared to webforms - which means it should be the same or better in terms of performance.

Hope this helps,

Scott

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

Thursday, December 6, 2007 11:34 PM by ScottGu

Hi 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?

Yep - I'll cover form posts and submit data scenarios with my next post.

ViewPage derives from Page - so it does have the same events as on Page today.  It doesn't execute the postback process on a request, though, so ceretain events will never execute.

Hope this helps,

Scott

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

Thursday, December 6, 2007 11:36 PM by ScottGu

Hi 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?

You could implement this one of two ways:

1) Use a master page and have all of the views based on it.  That way the common functionality is defined once.

2) Use controls (either user controls or compiled server controls) to encapsulate your rendering logic and add them into your views like you do today.  This provides an easy way to share content/view code across a site.

Hope this helps,

Scott

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

Thursday, December 6, 2007 11:37 PM by ScottGu

Hi Gagan,

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

You can technically return any type of content from your view - so XAML would ceretainly be one option you could use.

Hope this helps,

Scott

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

Thursday, December 6, 2007 11:40 PM by ScottGu

Hi Ben Hayat,

>>>>>>>> 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?

Controls that don't do postback will work within MVC views.  Controls that perform postback, though, will need to be updated to instead post to controller actions instead of back to themselves on a page.

Hope this helps,

Scott

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

Thursday, December 6, 2007 11:41 PM by MIke Geise

I was wondering if the framework support "area" like castle monorail does. Say I have MemberController.cs and ProfileController.cs and I want to do /member/profile/view.aspx instead of /profile/view.aspx.

Thanks, Mike

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

Thursday, December 6, 2007 11:43 PM by ScottGu

Hi Jim,

>>>>>>> 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?

We ship a ViewMasterPage class that your master pages can derive from.  This class has a ViewData dictionary api that you can then to access the view from the master.  There is also a ViewMasterPage<T> base class if you want to obtain a strongly typed API version.

One approach I recommend using is to define a MasterViewData class for the site, and then have all of your view specific viewdata classes derives from it.  For example:

public class MasterViewData {

   public string Title { get; set; }

}

public class ProductsListViewData : MasterViewData {

   public string         CategoryName { get; set; }

   public List<Product>  Products { get; set; }

}

The benefit of this approach is that you can then pass in any of the masterpage specific view data settings from any Controller Action method.  

Hope this helps,

Scott

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

Thursday, December 6, 2007 11:46 PM by ScottGu

Hi Damsel in Distress,

>>>>>>> This sums up to 6 web development platforms by Microsoft.  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?

In general there are two web application UI technologies that I recommend using/looking at:

- ASP.NET (either WebForms or MVC) with AJAX

- Silverlight

I'd recommend using ASP.NET for all of your server-side code, and to use AJAX where it makes sense to light-up an application whose logic is primarily server driven.

Silverlight (especially with Silverlight 2.0) makes sense in cases where much of your application/UI logic can/should live on the client-side.  It will enable you to build super rich web browser experiences with maximum interactivity.

Hope this helps,

Scott

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

Thursday, December 6, 2007 11:50 PM by ScottGu

Hi MKidder,

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

The ProductsListViewData class could be defined either in the ProductsController.cs file, or in another class file in the project.  There is not technical difference between doing the two - it pretty much comes down to personal preference.  

Hope this helps,

Scott

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

Thursday, December 6, 2007 11:51 PM by ScottGu

Hi John Shissler,

>>>>>>> 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.  

Yes - we are looking to have the ASP.NET AJAX Control Toolkit have MVC equivalents to all the built-in AJAX widgets.

Hope this helps,

Scott

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

Thursday, December 6, 2007 11:57 PM by ScottGu

Hi Kapil,

>>>>>>> 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?

In general I think people who use the MVC framework will do it for one of two reasons:

1) Testabiliy and the unit testing support of it

2) Ability to write code that is a little lower in the abstraction stack than WebForms.  If you want total control over your HTML and URL structure, then the MVC framework has some benefits.  If you want to work at a higher level abstraction (controls with more built-in functionality) then webforms is a better fit for you.  Both are perfectly valid approaches - it really comes down to whatever you feel more comfortable with and whichever feels most natural.

Hope this helps,

Scott

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

Thursday, December 6, 2007 11:58 PM by ScottGu

Hi Mike,

>>>>>>>> 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.

Actually - in my samples above in this post I'm using a declarative repeater control within my MVC view as an alternative to using a foreach loop.  So you can do this too. :-)

Thanks,

Scott

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

Thursday, December 6, 2007 11:59 PM by ScottGu

Hi Steve,

>>>>>>> I'd like to see how Ajax gets implemented with this new framework

I'll be covering this in future tutorial posts.  We definitely have a plan to nicely integrate it. :-)

Thanks,

Scott

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

Friday, December 7, 2007 12:00 AM by ScottGu

Hi Shailen,

>>>>>>> Just on the ProductsListViewData class, doesn't it have to inherit from a base class to indicate it holds viewstate data? It will work fine in the strongly typed scenario but in the the reflection based scenario, it would be good if the ASP.Net engine can at least know that the given viewstate class is a ViewState type of class.

No - there is actually no need to derive from any base class with this.  You can pass in any plain old object as the ViewData.

Hope this helps,

Scott

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

Friday, December 7, 2007 12:02 AM by ScottGu

Hi Lance,

>>>>>>>> I was wondering if it would be possible through the use of server controls or another tool to change this code:

>>>>>>>> <% foreach (var product in (ViewData["Products"] as List<Product>)) { %>

>>>>>>>>   <li>

>>>>>>>>      <%= product.ProductName %>

>>>>>>>>   </li>

>>>>>>>> <% } %>

>>>>>>>> Into something more like this:

>>>>>>>> <my:Products>

>>>>>>>>   <li>

>>>>>>>>      <my:ProductName />

>>>>>>>>   </li>

>>>>>>>> </my:Products>

Yes - you could use an approach like that if you wanted to.  The ASP.NET page compiler is pretty fleible, and allows you to build server controls that support declarative markup structures like that if you want.

Hope this helps,

Scott

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

Friday, December 7, 2007 12:06 AM by ScottGu

Hi Mike,

>>>>>>>> I was wondering if the framework support "area" like castle monorail does. Say I have MemberController.cs and ProfileController.cs and I want to do /member/profile/view.aspx instead of /profile/view.aspx. Thanks, Mike

The best way to support this today would be to setup a routing rule to handle it.  They allow flexible mapping of any arbitrary URL to a controller - and would definitely support that.  I talk about URL routing rules here: weblogs.asp.net/.../asp-net-mvc-framework-part-2-url-routing.aspx

You'd probably want to add a rule like below to handler your Profile scenario:

           routes.Add(new Route

           {

               Url = "Member/Profile[action]/[id]",

               Defaults = new { controller = "Profile", id = (string)null },

               RouteHandler = typeof(MvcRouteHandler)

           });

Hope this helps,

Scott

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

Friday, December 7, 2007 12:11 AM by jay

hi scott,

can you provide source code of this article please.

Thanks

jay

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

Friday, December 7, 2007 4:02 AM by Mike

>>>>>> Actually - in my samples above in this post I'm using a declarative repeater control within my MVC view as an alternative to using a foreach loop.  So you can do this too. :-)

Completely overlooked it, because the images were not rendering in your blog when I read it. Maybe you can switch to posting code instead of screen shots?

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

Friday, December 7, 2007 4:16 AM by Erik

Hi Scott, thanks for another excellent article on ASP.NET MVC. =) My question for you is that there are two distinct ways to pass ViewData - either via a dictionary or a strongly-typed data object. Is it possible to combine the two? That is, say I have a viewdata object named MyViewData, and my view inherits from ViewPage<MyViewData>, can I still have the controller pass data not held in MyViewData to the view for consumption?

Thanks! =)

Erik

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

Friday, December 7, 2007 4:20 AM by Anil

Hi Scott,

This would be great stuff.. eagerly waiting to see the code ....

Will the LINQ to SQL take care of object/query caching?

Regards,

Anil.

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

Friday, December 7, 2007 5:42 AM by Jose

Hi Scott, I would like to see how to make Ajax enabled applications. MonoRail has helpers to create HTML code to make forms 'ajaxified', and to render partial views, and I would like to have it in ASP.Net MVC

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

Friday, December 7, 2007 6:54 AM by Lachlan

Hi Scott,

Just read all 3 of these articles, very well written! I'm very excited about this framework. I've been using asp.net since it came out and I always missed having a flexible UI framework like struts or webwork (having come from a j2ee background). This implementation looks fantastic, personally I never liked the event driven model of web forms as much as a more pure MVC approach.

Thanks for the posts,

Lachlan

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

Friday, December 7, 2007 7:30 AM by lkempe

Hi Scott,

Nice to see you and your team going on that direction!

What can we expect concerning PageFlow ? I know that a project was started quite some time ago and we didn't hear anything about it anymore. I guess it is due to the MVC Framework, or? So do you consider such a pageflow solution for MVC ?

Now that we have a clear separation of the Model, Controller and View do you see a re-use of this architecture, let say on Silverlight 2.0 ?

I have implemented my portal (www.TechHeadBrothers.com) using WebParts, how do you see MVC and WebParts working together ?

Regards

Laurent Kempé

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

Friday, December 7, 2007 9:35 AM by The Other Steve

Today is tomorrow.  Where's the MVC?

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

Friday, December 7, 2007 9:56 AM by weareu

Scott, Please don't let us down today... PLEASE! I can't find the post where you said that it'll be today, so I'm asuming you deleted it... Again, Please don't let us down today!

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

Friday, December 7, 2007 10:03 AM by Shawn Smith

Checks under the tree for the tenth time this morning. :-)

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

Friday, December 7, 2007 10:27 AM by Web Developer Dude

Isn't there a law in the US against torture? You keep showing us all the coolness of your wonderful framework, but we can't play with it yet!!!

Just kidding...but I can't wait to see this thing in action!!!!

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

Friday, December 7, 2007 11:05 AM by Anthony

Nice blog Scott,

I can't wait to get my hands dirty on this MVC Framework for Asp.Net. Any idea when it will be available?

greetz from Belgium

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

Friday, December 7, 2007 12:49 PM by Ben

Yes it is frustrating, few blogs back Scott clearly stated it would be out

same day as VS 2008 RTM, he then said recently definitely the end of this week. :-(

Scott - is only bug fixing the major hold up or are more features being sneaked in at the last minute? ;-)

Also it would be great if there was some form of roadmap for the MVC in 2008 - is this likely to appear after the initial CTP?

Thanks and looking forward to Monday I hope!

Ben

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

Friday, December 7, 2007 12:49 PM by Mariano

Please!! No more torture!! Give us MVC!

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

Friday, December 7, 2007 2:14 PM by Francois Ward

This is looking sweet, but I have a question.

Except for people who REALLY like MVC (which is many, many people, but I'm not one of em), this is sweet, not because of the MVC approach, but because it is a more complete framework than the webforms.

That is, at first glance, more things were thought of in this, and it will integrate better with a lot of methods and such, plus it will be a core .NET technology.

Now, webforms can do all these things: mainly if you use Model View Presenter and add a bit of code. This does exist: in the Web Client Software Factory. However, the WCSF isn't part of Visual Studio, and while its made by Microsoft, it has a very "third party" feel to it, in how its supported and developed, as opposed to the MVC.

Are there plans to enhance webforms natively to give them the advantages of a full framework, like the ASP.NET MVC, part of the main offering?

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

Friday, December 7, 2007 4:01 PM by Jonathan Chavez

Scott said it will be available for today

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

Friday, December 7, 2007 6:20 PM by Mike

>>>>>>>> (weareu) Scott, Please don't let us down today... PLEASE! I can't find the post where you said that it'll be today, so I'm asuming you deleted it... Again, Please don't let us down today!

Wow it really was removed I remember reading it as well and he said they planned on it being today. Seems like that won't happen. They should not say when they are going to release a preview of something because all it does is generate bad feedback for them when they don't meet that date for the preview. Especially since this is in high demand atm.

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

Friday, December 7, 2007 6:31 PM by Gauthier Segay

to Wesley Bakker:

"""

To me this (www.scottgu.com/.../step8.png) looks like we're going back to the good old spaghetti coded ASP pages. Progress? I don't know yet.

"""

to me, it feels far more readable than datagrid (or such) tagsoup, I'm also concerned how the code behind look with control.on*bound handlers mess.

After all, I think it's individual taste affair, and I'm glad that asp.net framework will soon officialy support both mindset.

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

Friday, December 7, 2007 7:24 PM by ripster

Hi,

Can we get some sort of idea how this framework is used to build applications that need to create/update data items (whether those items live in a database or not). From my (admittedly brief) look through the details of these articles all I can see is a different way to display data (ala brochure-ware).

I spend most of my time building apps that have a create/update requirement so I'd like to see if this framework will help me in any way.

Cheers,

ripster

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

Friday, December 7, 2007 8:47 PM by xiaohua liu

It is a pretty nice article. A quick question here: Can the view form handle the postback events in MVC framework?

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

Friday, December 7, 2007 9:23 PM by ScottGu

Quick update to everyone - we found a last minute bug late last night, and had to-do a rebuild of the bits.  This unfortunately means we won't go live today as origionally planned.  The team is working hard, though, to try and get it out ASAP (they will be here this weekend finishing the test pass).  

I'll do a blog post announcing it as soon as it is live.  As penance I'm also doing a long Part 4 blog post this weekend that covers editing and form posting scenarios, which combined with the first three tutorial posts should provide a pretty good foundation for working with the bits.

Many apologies for the delay - almost there now though,

Scott

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

Friday, December 7, 2007 10:00 PM by Mike

So not this weekend though right?

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

Friday, December 7, 2007 10:06 PM by Vanilla Developer

Hi Scott,

I've always enjoyed your blog because you have practical information that most of us developers out here in the trenches can use.

The MVC - IN MY OPINION - is one of those examples of over engineering you sometimes find in our industry.

Hopefully we can entice your keyboard back to the land of us mere mortals soon :-)

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

Friday, December 7, 2007 10:21 PM by Rob Bazinet

Thanks for the update Scott.  I think we all know how easy it is to having problems meeting a deadline, even if it's self-imposed.

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

Saturday, December 8, 2007 3:33 AM by waiting patiently

I'm sure everyone's looking forward to the bits, but shouldn't the team be playing xbox live or something on the weekend instead of working on bug fixes? I wouldn't complain about waiting till next week, I'll be playing Halo 3 ;)

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

Saturday, December 8, 2007 8:00 AM by Lance Fisher

To you and the MVC team: thanks for all your hard work!  I'll be eagerly awaiting the post and bits!

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

Saturday, December 8, 2007 8:16 AM by ranunes

Scott,

Works in ASP .NET 2.0?

Thanks

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

Saturday, December 8, 2007 8:20 AM by Andy

Just read Rob Conery's blog post on the MVC UI Helpers. The new features from C# 3.0 look very flexible. And databinding via UpdateFrom seems a good clean approach. Can't wait to tie in these Preview elements with the Ext JS 2.0 javascript library. Surely together the ultimate MVC toolkit?!

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

Saturday, December 8, 2007 11:20 AM by The Other Steve

I have to admit, this is what is better about open source.  I would have had this already, and been spending the last few weeks experimenting with it.

As much as I like working with .NET and Windows, it's hard not to be disappointed.  Something like this MVC really should be released as source by Microsoft anyway, and I don't mean the source when it's done.  The development could be open to the public via codeplex.com.

sigh

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

Monday, December 10, 2007 1:43 PM by Travis

I cannot access server side web controls in my View from the view's code behind like the example above.  Has something changed for today's release?

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

Monday, December 10, 2007 8:26 PM by David

I am very impressed with the MVC Framework, and would love to find out more when using User Controls (ascx) and Masterpages.  Specificaly how do we pass data to a master page, we cant use ViewData because it is not a ViewPage :( and we would not want to pass it via a particular controller.

With User Controls how do I access the ViewContext so that I can create a HtmlUtility class?

Any chance for some clarification on this?

Regards,

David

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

Tuesday, December 11, 2007 3:42 AM by bolr

I have Created a mvc project, when i run it the action can be executed but the parameter of the action always are null. even i set a defaut value for the parameter.

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

Tuesday, December 11, 2007 2:37 PM by Denis

As travis stated...

I cannot access server side web controls in my View from the view's code behind like the example above.  

I am also experiencing the same problem; no ability to reference declared controls from the code-behind.

I sincerely hope I'm doing something wrong (refernce missing, improper declaration somewhere, ???). I certainly do NOT want to go back to the days of intertwining code with HTML.

I downloaded the MVCToolKit and Scott's Sample application expecting to see code-behind files implemented like the examples in this blog, and... no such luck. They were all code intertwined with html. Not a single server control to be had. Eeewwww!

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

Tuesday, December 11, 2007 2:46 PM by Denis

Sorry for the last complaint... I found the work-around on Scott's next blog:

----------------------------------

Monday, December 10, 2007 12:03 AM by ScottGu

Hi John and Sitem00n,

>>>>>>> I downloaded the preview, and tried using a Repeater control like some of your sample code shows, and it does not seem to work. The control does not even appear to exist as far as the code-behind is concerned. What am I doing wrong?

There is an issue with the default file templates that you use to create view pages with the MVC project.  They unfortunately by default don't generate the .designer.cs/.vb files that are used by the code-behind to get intellisense for controls - which is why you are running into the issue you are seeing.

The good news is that this is easy to fix.  Just select your file in the solution explorer, right click, and choose the "Convert to Web Application" context menu option.  This will generate the .designer file for you.  From that point on, all changes you make to the .aspx file will be reflected in the code behind, and you'll be able to databind declaratively using the <asp:repeater> control.

Hope this helps,

Scott

-----------------------------

I tried it and it works!!!

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

Tuesday, December 11, 2007 10:31 PM by Fisher Ning

Hi Scott,

I got the error 'A ViewMasterPage<TViewData> can only be used with content pages that derive from ViewPage<TViewData>.' when I follow your steps:

One approach I recommend using is to define a MasterViewData class for the site, and then have all of your view specific viewdata classes derives from it.  For example:

public class MasterViewData {

  public string Title { get; set; }

}

public class ProductsListViewData : MasterViewData {

  public string         CategoryName { get; set; }

  public List<Product>  Products { get; set; }

}

The benefit of this approach is that you can then pass in any of the masterpage specific view data settings from any Controller Action method.

Could you give me some advice?

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

Wednesday, December 12, 2007 1:38 AM by ScottGu

Hi Mike,

>>>>>> Scott - is there a way in the MVC framework to make a controller's action load a different view based upon an arbitrary extension?  So I might have:

Yes - we'll have the ability to load different views depending on format values passed in as part of the URL.  The routing system is rich enough to enable this to be parameterized.

Thanks,

Scott

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

Wednesday, December 12, 2007 1:40 AM by ScottGu

Hi Travis,

>>>>>>>>> I cannot access server side web controls in my View from the view's code behind like the example above.  Has something changed for today's release?

There is an issue with the default file templates that you use to create view pages with the MVC project.  They unfortunately by default don't generate the .designer.cs/.vb files that are used by the code-behind to get intellisense for controls - which is why you are running into the issue you are seeing.

The good news is that this is easy to fix.  Just select your file in the solution explorer, right click, and choose the "Convert to Web Application" context menu option.  This will generate the .designer file for you.  From that point on, all changes you make to the .aspx file will be reflected in the code behind, and you'll be able to work with any control in the .aspx markup.

Hope this helps,

Scott

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

Wednesday, December 12, 2007 1:41 AM by ScottGu

Hi David,

>>>>>> I am very impressed with the MVC Framework, and would love to find out more when using User Controls (ascx) and Masterpages.  Specificaly how do we pass data to a master page, we cant use ViewData because it is not a ViewPage :( and we would not want to pass it via a particular controller.  With User Controls how do I access the ViewContext so that I can create a HtmlUtility class?

I'm planning on covering this in some future blog posts.  At a high-level, though, you can access the view from both MasterPages and from UserControls (there are ViewPage-like base classes for both).

Thanks,

Scott

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

Wednesday, December 12, 2007 1:41 AM by ScottGu

Hi Bolr,

>>>>>>> I have Created a mvc project, when i run it the action can be executed but the parameter of the action always are null. even i set a defaut value for the parameter.

Can you try posting your code snippet here: forums.asp.net/1146.aspx

The team can then help you get this fixed.

Thanks,

Scott

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

Wednesday, December 12, 2007 1:42 AM by ScottGu

Hi Denis,

I just responded to Travis above about the code-behind controls issue.  If you follow the steps I listed above it will fix it.

Thanks,

Scott

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

Wednesday, December 12, 2007 1:43 AM by ScottGu

Hi Fisher,

>>>>>>> I got the error 'A ViewMasterPage<TViewData> can only be used with content pages that derive from ViewPage<TViewData>.' when I follow your steps

Unfortunately it turns out there is a bug right now where an error is raised of the MasterPage and the ViewPage are based on different ViewData structures.  We'll get this fixed for the next CTP.

Thanks,

Scott

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

Wednesday, December 12, 2007 11:00 PM by bolr

Hi Scott,

>>>>>>> I have Created a mvc project, when i run it the action can be executed but the parameter of the action always are null. even i set a defaut value for the parameter.

I have resolved the issue, that is because i made a mistake, the parameter name must be same with the Route default value name and Html.ActionLink object parameter name,but i ...

Anyway thank you very much.

BTW: Why the MVC framework doesn't support .ashx view template

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

Thursday, December 13, 2007 6:23 AM by Harry Solsem

I found the url to download the project form You part 4 of this blog.

Any url to download the code from the mvc toolkit blogs (parts 1-3)?

Harry

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

Friday, December 21, 2007 2:11 AM by kdpo1990

I just love coming here and studding something new every time. I just wish I found the way to convince my boss to use this great technology, and not WebDynpo.

Sad to say, but my company is moving away from ASP.NET. , And I see WebDynpo as a downgrade.

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

Sunday, January 6, 2008 2:41 PM by Jay

Hi Scott, please tell us when the source code for the "A Simple E-Commerce Storefront Application" will be released?

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

Wednesday, January 23, 2008 3:37 AM by Nan Jiang

I have a question:

I repeated your sample code in this article, but I found that I can not access any Server Control instances of a MVC View page in its corresponding code behind C# file:

in aspx file:

<asp:Label  ID="CategoryName" runat="server">

</asp:Label>

when I wrote the code to access the property of CategoryName in Page_Load method, the compiler said: "The name 'CategoryName' does not exist in the current context".

does any one have the same problem?    :(

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

Wednesday, January 23, 2008 4:27 AM by Nan Jiang

In my test, with following MVC view page:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="AllProducts2.aspx.cs" Inherits="MvcApplication.Views.Product.AllProducts2" Title="Untitled Page" %>

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

<asp:GridView ID="GridView1" runat="server" >

</asp:GridView>

<asp:Label  ID="CategoryName" runat="server" >

</asp:Label>

</asp:Content>

an exception was thrown when browsing:

Control 'ctl00_MainContentPlaceHolder_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.

I have to add a <form runat="server"> to inclose all server control to avoid this exception.

I am using xp sp2, vs2008 and IIS6.   any one has the same problem?  

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

Friday, February 1, 2008 1:49 PM by AJ

Yes Nan Jiang. I am facing the same problem. Did you find a solution?

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

Sunday, February 3, 2008 1:01 AM by Liio

Wednesday, January 23, 2008 3:37 AM by Nan Jiang

I have a question:

I repeated your sample code in this article, but I found that I can not access any Server Control instances of a MVC View page in its corresponding code behind C# file:

in aspx file:

<asp:Label  ID="CategoryName" runat="server">

</asp:Label>

when I wrote the code to access the property of CategoryName in Page_Load method, the compiler said: "The name 'CategoryName' does not exist in the current context".

does any one have the same problem?    :(

I also encountered the same problem....did rob run this sample application first before he wrote this tutor article??  

Help.