ASP.NET MVC Source Refresh Preview

We recently opened up a new ASP.NET CodePlex Project that we will be using to provide previews (with buildable source code) for several upcoming ASP.NET features and releases.

Last month we used it to publish the first drop of the ASP.NET MVC source code.  This first drop included the source for the ASP.NET MVC Preview 2 release that we shipped at MIX, along with Visual Studio project files to enable you to patch and build it yourself.

A few hours ago we published a refresh of the ASP.NET MVC source code on the site.  This source refresh is not an official new ASP.NET MVC preview release - instead it is an interim drop that provides a look at the current state of the source tree.  We will ship the official "ASP.NET MVC Preview 3" release in a few weeks after we finish up some more work (more features and tweaks to existing ones, better VS tool integration, VS express edition support, documentation, etc).  If you are someone who wants a hassle-free installation of ASP.NET MVC to use that ships with documentation and full tool support you'll probably want to wait for this official preview release.  If you are someone who wants a chance to see an early "preview of the preview" and have the opportunity to start using and giving feedback on some of the features immediately, today's source refresh is probably interesting to look at.

Improvements with this ASP.NET MVC Source Refresh

This week's update (which you can download here) includes a number of improvements to ASP.NET MVC.  Some of these include:

  • In addition to posting the source code for the ASP.NET MVC framework, we are also posting the source code for the unit tests that we use to test it.  These tests are implemented using MSTest and the open source Moq mocking framework.  A VS 2008 project file for the unit tests is included to make it easy to build and run them locally within your VS 2008 IDE.

  • Significantly easier support for testing Controller classes.  You can now unit test common Controller scenarios without having to mock any objects (more details on how this works below).

  • Several nice feature additions and usability improvements to the URL routing system (more details below).

Creating a New ASP.NET MVC Project

You can build your own copy of the ASP.NET MVC assemblies by downloading the MVC source and compiling it locally, or alternatively you can download a VS Template package to get a pre-built version of them along with a Visual Studio project template that you can use to quickly build a new ASP.NET MVC Project that uses the latest bits.

After you install the ASP.NET MVC source refresh .VSI template, a new "ASP.NET MVC Application" project template will show up under the "My Templates" section of your "New Project" dialog:

This new "My Templates" version of the MVC project template lives side-by-side with the previous ASP.NET MVC Preview 2 release (which you can see above it in the main project templates section of the dialog).  This allows you to safely create new projects and and use both the latest source version and the last official preview version on the same machine.

When you create a new project using this updated ASP.NET MVC Project template you'll by default get a project that looks like below:

This new project solution contains one Controller ("HomeController") under the "\Controllers" directory and two View templates ("About" and "Index") under the "\Views\Home" sub-directory.  Both view templates are based on a common master page for the site ("Site.master"), all of whose styles are defined within a "Site.css" file under the "\Content" directory.

When you run the application the built-in web-server will automatically start up and you'll see the site's "Home" content:

Clicking the "About us" tab will then display the "About" content:

The "HomeController" class in the project is responsible for handling both of the URLs above and has two action methods like below:

The default "Site.master" template looks for a "Title" value in the ViewData collection and uses it to render the <title> element of the HTML page.  The default "Index" view template looks for a "Message" value and uses it to render the home page's welcome message.  You can obviously go in and customize these files however you want.

Controller Changes with this ASP.NET MVC Drop

If you were reading the above code closely you might have noticed a few changes with how Controller classes are by default implemented using this new ASP.NET MVC source refresh drop. 

With the ASP.NET MVC Preview 2 release the above HomeController action methods would have instead been implemented like below:

The MVC feature team is experimenting with a few ideas in this week's drop and are trying out some new ideas:

  1. Action methods on Controllers now by default return an "ActionResult" object (instead of void).  This ActionResult object indicates the result from an action (a view to render, a URL to redirect to, another action/route to execute, etc). 

  2. The RenderView(), RedirectToAction(), and Redirect() helper methods on the Controller base class now return typed ActionResult objects (which you can further manipulate or return back from action methods).

  3. The RenderView() helper method can now be called without having to explicitly pass in the name of the view template to render.  When you omit the template name the RenderView() method will by default use the name of the action method as the name of the view template to render.  So calling "RenderView()" with no parameters inside the "About()" action method is now the same as explicitly writing "RenderView('About')".

It is pretty easy to update existing Controller classes built with Preview 2 to use this new pattern (just change void to ActionResult and add a return statement in front of any RenderView or RedirectToAction helper method calls).

Returning ActionResult Objects from Action Methods

So why change Controller action methods to return ActionResult objects by default instead of returning void?  A number of other popular Web-MVC frameworks use the return object approach (including Django, Tapestry and others), and we found for ASP.NET MVC that it brought a few nice benefits:

  1. It enables much cleaner and easier unit testing support for Controllers.  You no longer have to mock out methods on the Response object or ViewEngine objects in order to unit test the response behavior of action methods.  Instead, you can simply assert conditions using the ActionResult object returned from calling the Action method within your unit test (see next section below).

  2. It can make Controller logic flow intentions a little clearer and more explicit in scenarios where there might be two different outcomes depending on some condition (for example: redirect if condition A is true, otherwise render a view template it is false).  This can make non-trivial controller action method code easier to read and follow.

  3. It enables some nice composition scenarios where a FilterActionAttribute can take the result of an action method and modify/transform it before executing it.  For example: a "Browse" action on a ProductCatalog controller might return an RenderActionResult that indicates it wants to render a "List" view of products.  A FilterActionAttribute declaratively set on the controller class could then have a chance to customize the specific "List" view template rendered to be either List-html.aspx or List-xml.aspx depending on the preferred MIME type of the client.  Multiple FilterActionAttributes can also optionally be chained together to flow the results from one to another.

  4. It provides a nice extensibility mechanism for people (including ourselves) to add additional features in the future.  New ActionResult types can be easily created by sub-classing the ActionResult base class and overriding the "ExecuteResult" method.  It would be easy to create a "RenderFile()" helper method, for example, that a developer writing an action could call to return a new "FileActionResult" object.

  5. It will enable some nice Asynchronous execution scenarios in the future.  Action methods will be able to return an AsyncActionResult object which indicates that they are waiting on a network operation and want to yield back the worker thread so that ASP.NET can use it to execute another request until the network call completes.  This will enable developers to avoid blocking threads on a server, and support very efficient and scalable code.

One of the goals with this interim preview is to give people a chance to play around with this new approach and do real-world app-building and learning with it.

We will also post an alternative Controller base class sample that you can use if you still prefer the previous "void" action return approach.  We deliberately didn't include this alternative Controller base class in this source refresh drop, though, because we want to encourage folks to give the "ActionResult" return approach a try and send us their app-building feedback on it.

How To Unit Test Controller Action Methods

I mentioned above that the new ActionResult approach can make unit testing controllers much easier (and avoid the need to use mocking for common scenarios).  Let's walk through an example of this in action.

Consider the simple NumberController class below:

This Controller class has an "IsEvenNumber" action method that takes a number as a URL argument.  The IsEvenNumber action method first checks whether the number is negative - in which case it redirects the user to an error page.  If it is a positive number it determines whether the number is even or odd, and renders a view template that displays an appropriate message:

Writing unit tests for our "IsEvenNumber" action method is pretty easy thanks to the new ActionResult approach.

Below is an example unit test that verifies that the correct Http redirect occurs when a negative number is supplied (for example: /Number/IsEvenNumber/-1):

Notice above how we did not need to mock any objects to test our action method.  Instead we simply instantiated the NumberController class and called the action method directly (passing in a negative number) and assigned the return value to a local "result" variable.  I used the C# "as type" syntax above to cast the "result" variable as a strongly typed "HttpRedirectResult" type.

What is nice about the C# "as" keyword is that it will assign the value as null instead of throwing an exception if the cast fails (for example: if the action method returned a RenderViewResult instead).  This means I can easily add an assertion check in my test to verify that the result is not null in order to verify that an Http redirect happened.  I can then add a second assertion check to verify that the correct redirect URL was specified.

Testing the scenarios where non-zero numbers are passed in is also easy.  To do this we'll create two test methods - one testing even numbers and one testing odd numbers.  In both tests we'll assert that a RenderViewResult was returned, and then verify that the correct "Message" string was passed within the ViewData associated with the view:

We can then right click on our NumberControllerTest class inside VS 2008 and choose the "Run Tests" menu item:

This will execute our three unit tests in-memory (no web-server required) and report back on whether our NumberController.IsEvenNumber() action method is performing the right behavior:

Note: with this week's source drop you still need to use mocking to test the TempData property on Controllers.  Our plan is to not require mocking to test this with the ASP.NET MVC Preview 3 drop in a few weeks.

MapRoute Helper Method

URL routing rules within ASP.NET MVC applications are typically declared within the "RegisterRoutes" method of the Global.asax class.

With ASP.NET MVC Previews 1 and 2 routes were added to the routes collection by instantiating a Route object directly, wiring it up to a MvcRouteHandler class, and then by setting the appropriate properties on it to declare the route rules:

The above code will continue to work going forward.  However, you can also now take advantage of the new "MapRoute" helper method which provides a much simpler syntax to-do the same thing.  Below is the convention-based URL route configured by default when you create a new ASP.NET MVC project (which replaces the code above):

The MapRoute() helper method is overloaded and takes two, three or four parameters (route name, URL syntax, URL parameter default, and URL parameter regular expression constraints). 

You can call MapRoute() as many times as you want to register multiple named routes in the system.  For example, in addition to the default convention rule, we could add a "Products-Browse" named routing rule like below:

We can then refer to this "Products-Browse" rule explicitly within our Controllers and Views when we want to generate a URL to it.  For example, we could use the Html.RouteLink view helper to indicate that we want to link to our "Products-Browse" route and pass it a "Food" category parameter using code in our view template like below:

This view helper would then access the routing system and output an appropriate HTML hyperlink URL like below (note: how it did automatic parameter substitution of the category parameter into the URL using the route rule):

Note: with this week's source drop you need to pass-in the controller and action parameters (in addition to the Category param) to the Html.RouteLink() helper to resolve the correct route URL to generate.  The ASP.NET MVC Preview 3 drop in a few weeks will not require this, and allow you to use the Html.RouteLink call exactly as I've written it above to resolve the route.

Other URL Route Mapping Features

This week's MVC source drop also supports a bunch of new URL route mapping features.  You can now include "-", ".", ";" or any other characters you want as part of your route rules.

For example, using a "-" separator you can now parse the language and locale values from your URLs separately using a rule like below:

This would pass appropriate "language", "locale", and "category" parameters to the ProductsController.Browse action method when invoked:

URL Route Rule Example URL Parameters Passed to Action method
{language}-{locale}/products/browse/{category} /en-us/products/browse/food language=en, locale=us, category=food
  /en-uk/products/browse/food language=en, locale=uk, category=food

Or you can use the "." file extension type at the end of a URL to determine whether to render back the result in either a XML or HTML format:

This would pass both "category" and a "format" parameters to the ProductsController.Browse action method when invoked:

URL Route Rule Example URL Parameters Passed to Action method
products/browse/{category}.{format} /products/browse/food.xml category=food, format=xml
  /products/browse/food.html category=food, format=html

ASP.NET MVC Preview 2 introduced wildcard route rules.  For example, you can indicate in a rule to pass all remaining URI content on as a named parameter to an action method:

This would pass a "contentUrl" parameter to the WikiController.DisplayPage action method when invoked:

URL Route Rule Example URL Parameters Passed to Action method
Wiki/Pages/{*contentUrl} /Wiki/Pages/People/Scott contentUrl="People/Scott"
  /Wiki/Pages/Countries/UK contentUrl="Countries/UK"

These wildcard routes continue to work fine with this week's preview - and are very useful to look at if you are building a blogging, wiki, cms or other content based system.

Note that in addition to using the new routing system for ASP.NET MVC scenarios, we are also now using the same routing system within ASP.NET Dynamic Data (which uses ASP.NET Web Forms).

Summary

Hopefully the above post provides a quick update on some of the new features and changes exposed with this week's ASP.NET MVC source update drop. 

You can download it here if you want to start using it immediately.  Alternatively, you can wait a few weeks for the official ASP.NET MVC Preview 3 drop - which will have some more features (and incorporate feedback people provide on this week's drop), deliver a more seamless installer, provide nice VS integration, and deliver up to date documentation.

For any questions/issues with this week's drop of ASP.NET MVC, make sure to also check out the ASP.NET MVC forum on www.asp.net.

Hope this helps,

Scott

77 Comments

  • Interesting approach, returning a ActionResult does seam to make testing a lot easier.


  • Hi Scott, from the moment Routing was moved in an independent assembly, I cannot see any good reason not to use Routing with ASP.NET. Building a custom cotroller is very simple. I can use server controls, i have the full power of the designer, there is NO reason to use MVC, and I really tried, but productivity is not as expected.
    What bothers me is that Intellisense works everywhere in a MVC view, but does not work in classic ASPX page inside attributes. It seems that MVC uses a hack or something. Do you have an idea, please, how to configure ASPX editor to use Intellisense inside attributes:

    <a href="">.?

  • A lots of amazing things done.

  • Thanks for adding the ActionResult, it will make my life better when using TDD, less mocking, less code, and much much nicer code.. Keep up the good work!

  • Thanks for making testing controllers infinitely easier.
    I like what's been done with the attributes too.

    What about custom pluggable string EncDec in routing?

  • Do you think DynamicData will ever be Codeplexed? That would be the best thing on the planet.

  • This is all great news! Good work. I really like the ActionResult.

    Is it possible set up routes or parameters to action methods based on the host header in the request, or other arbitrary request headers? Suppose I have two domains pointed at the same site. I'd like to send requests for mysite.com/products to the products action on the home controller, but requests for customer.com/products to a different action method that handles "products" as a wild card route.

  • I try to describe in a forum post here http://forums.asp.net/t/1247307.aspx

    Basically, I'm trying to customize the encoding/decoding of action method string arguments in URLs at the routing level of things.

    Let's say I install my custom EncDec and an action:
    ActionResult MyAction(string name) {}

    Then calling Url.ActionLink(c => c.MyAction("a blog post"),"link name") would return /MyController/MyAction/a-blog-post

    These segments EncDecs schemes are usually non-reversible, so uniqueness must be checked unless it's persisted in the db (a la` SubText). The non-reversible quality of these algorithms may mean that what I'm asking is impossible - but I'm curious what the pros think.

    Once again, great work!

  • MS MVC gets more interesting and powerful day by day.. I really like the new MapRoute method. It's much cleaner and readable than the RegisterRoutes method.

  • Hi,

    Will this new official preview version 3, support dynamic languages.

    Its great to know about VS express support with version 3.0, when do you plan to share thew news about dynamic languages support with asp.net mvc...?

  • Hello Scott,
    I am keep watching MVC Framework and every thing you are creating makes me very happy. I desperately expect to see best mechanism or approach for “Input data validation”.
    I feel it one of the most import things in application development and looking for you positive reply.

    Thanks,
    Nagarajan.

  • Good to see the source released, it's interesting to read.

    Are you guys considering more options for subdividing a project? What I mean is that you could have these routes:

    {A}/{Controller}/{Action}
    {B}/{Controller}/{Action}

    And it would automagically find the controllers (and views) in the subfolders A and B, because it would help to keep the folder layout clear.

  • The new ActionResult is way better for testing controllers... thanx for listening to all of us :)

  • Then, a not a comment about the new features but about the formatting of the post.
    The posts that contain images with codesnippets with the black background are impossible to read when printed on a black and white printer (and too much ink used when printing in color). Not sure how you can improve the thing without loosing the dark VS color schema we all love. Maybe just add the snippets also as downloadable file? or maybe have a different image to showup when printed (using the print css)?

  • No support for a default controller when no controller is found? I want this for graceful 404 handling instead of throwing the nasty exception it currently does!

  • I like ActionResult approach, however IMHO "return RenderView()" becomes a confusing name for something that is returning an object instead of executing render view logic just in that moment. What about something like "return GetRenderViewAction()" or "return GetRenderViewDescriptor()" or something similar ?

  • Thanks for good post. It's really interesting idea of "preview of preview" that allows us to play with newest features and allows team make some reasonable code-response based on feedback up to official preview release.

    P.S. Waiting for full implementation of view helper logic you introduced.

  • When will ASP.Net MVC be production?

  • Is Preview 3 supporting Visual Web Developer 2008?

  • > A FilterActionAttribute declaratively set on the controller class could then have a chance to customize the specific "List" view template rendered to be either List-html.aspx or List-xml.aspx depending on the preferred MIME type of the client.

    Being able to change the ViewName of the RenderViewResult is a great idea. This does give a very clear direction for the 101 samples on blogs of providing different serialisation formats, using a custom ViewPage.

  • When the the MVC framework have a RC?

  • Great post and sample. Thanks.

  • This is awesome... Thanks for posting this to codeplex. I can't wait to migrate yonkly.com to the new code refresh. I will report back/blog on migration issues.

  • Hi Scott,

    Any chance you could share the VS color scheme you're using?

    Thanks

  • I'm confused what type of object is being instantiated with the following syntax:

    new { Category="Food" }

    Does this just return an anonymous object, like the "var" syntax?

    Thanks in advance.

  • Html.RouteLink (Preview 3) == Html.ActionLink (Preview 2) ?

  • "Hi Scott, Any chance you could share the VS color scheme you're using? Thanks" -- Anton

    Funny, that was my first thought as well. Not "hey cool new features" but instead "hmm, either Scott changed his theme or got someone else to ghost write this".

    We are such nerds.

  • Thanks for the update Scott. I downloaded the source code, compiled and ran the templates .vsi file, created a new ASP.NET MVC web application with the new template under My Templates, and tried to run the new app. I get the following error: "Could not load file or assembly 'System.Web.Mvc' or one of its dependencies. Strong name signature could not be verified. The assembly may have been tampered with, or it was delay signed but not fully signed with the correct private key. (Exception from HRESULT: 0x80131045)".

    Any ideas?

  • Great but... after "upgrade" (change void to ActionResult) my project doesn't work. Views are not rendered. :( MVC not seeing my Default.aspx and I got 404 :( Why?

  • Awesome, this is going to make testing a lot easier.
    One question. When calling RenderView(), it doesn't seem to set the ViewName in the result, which doesn't allow unit tests to verify the correct view was created.
    Is it enough to test that the result is the correct type and not null? I would think it would be a good idea to still test the view name to make sure it's not creating a different view.

  • Hi Liviu,

    >>>>>>> What bothers me is that Intellisense works everywhere in a MVC view, but does not work in classic ASPX page inside attributes. It seems that MVC uses a hack or something. Do you have an idea, please, how to configure ASPX editor to use Intellisense inside attributes: <a href="">.?

    Unfortunately neither MVC nor WebForms currently supports intellisense within attributes. You get color coding (and compile-time checking) but no intellisense. That is something we are looking to enable in the future though (for both webforms and mvc).

    Thanks,

    Scott

  • Hi Lance,

    >>>>>> Is it possible set up routes or parameters to action methods based on the host header in the request, or other arbitrary request headers? Suppose I have two domains pointed at the same site. I'd like to send requests for mysite.com/products to the products action on the home controller, but requests for customer.com/products to a different action method that handles "products" as a wild card route.

    I think you can vary routes based on headers - although I am not 100% sure (have you tried posting in the MVC forums to get an answer?). You can definitely vary based on http verb (which is a header), so I suspect there is a way to handle other header values as well.

    Thanks,

    Scott

  • Hi softmind,

    >>>>>> Will this new official preview version 3, support dynamic languages.

    Dynamic language and DRL support is coming. Expect more samples on this soon.

    Thanks,

    Scott

  • Hi random0xff,

    >>>>>>> Are you guys considering more options for subdividing a project? What I mean is that you could have these routes:

    >>>>>>> {A}/{Controller}/{Action}
    >>>>>>> {B}/{Controller}/{Action}

    >>>>>>> And it would automagically find the controllers (and views) in the subfolders A and B, because it would help to keep the folder layout clear.

    You can actually change the folder structure today however you want for controllers (there are no hard-coded rules). By default it resolves controllers based on type and namespace name - so you can put them into any subfolders you want.

    Hope this helps,

    Scott

  • Hi John,

    >>>>>>> No support for a default controller when no controller is found? I want this for graceful 404 handling instead of throwing the nasty exception it currently does!

    You can add a final routes.MapRoute call at the end of your route registrations that maps everything else to your FileNotFoundController. This should work today.

    Hope this helps,

    Scott

  • Hi RafaH,

    >>>>>>>>> I like ActionResult approach, however IMHO "return RenderView()" becomes a confusing name for something that is returning an object instead of executing render view logic just in that moment. What about something like "return GetRenderViewAction()" or "return GetRenderViewDescriptor()" or something similar ?

    The team is still looking at different naming options to see if they can make it a little clearer.

    Thanks,

    Scott

  • Hi Shiju,

    >>>>>>>> Is Preview 3 supporting Visual Web Developer 2008?

    The Preview 3 in a few weeks will support VWD Express - not long off now.

    Thanks,

    Scott

  • Hi osbornm,

    >>>>>> When the the MVC framework have a RC?

    I think we have at least 1-2 preview drops before it goes to beta. We'll then have at least one beta before the final release.

    Thanks,

    Scott

  • Hi Anton,

    >>>>>>> Any chance you could share the VS color scheme you're using?

    Here is a copy of my VS color settings: http://www.scottgu.com/blogposts/aprilmvc/scottgu-dark.zip

    Thanks,

    Scott

  • Hi Mike,

    >>>>>>> I'm confused what type of object is being instantiated with the following syntax:

    >>>>>>> new { Category="Food" }

    >>>>>>> Does this just return an anonymous object, like the "var" syntax?

    That returns an anonymous type, which the Html.RouteLink helper method then uses to determine key/value pairs. I have a blog post here that talks more about how anonymous types work: http://weblogs.asp.net/scottgu/archive/2007/05/15/new-orcas-language-feature-anonymous-types.aspx?CommentPosted=true

    Hope this helps,

    Scott

  • Hi Dimi3,

    >>>>>>>> Html.RouteLink (Preview 3) == Html.ActionLink (Preview 2) ?

    No - we still have Html.ActionLink too. ActionLink is used when you know the exact controller/action pair to use. RouteLink allows you to generate the links based on a "named route" that you've explictly declared.

    Hope this helps,

    Scott

  • Hi PWills,

    >>>>>>> Funny, that was my first thought as well. Not "hey cool new features" but instead "hmm, either Scott changed his theme or got someone else to ghost write this".

    No ghost writing here - I was up till 3:30am Sunday writing this one (and then the team needed to delay to Wed to post the bits - sheesh). Here is my VS settings file: http://www.scottgu.com/blogposts/aprilmvc/scottgu-dark.zip

    Thanks,

    Scott

  • Hi Gabriel,

    >>>>>>>> Thanks for the update Scott. I downloaded the source code, compiled and ran the templates .vsi file, created a new ASP.NET MVC web application with the new template under My Templates, and tried to run the new app. I get the following error: "Could not load file or assembly 'System.Web.Mvc' or one of its dependencies. Strong name signature could not be verified. The assembly may have been tampered with, or it was delay signed but not fully signed with the correct private key. (Exception from HRESULT: 0x80131045)".

    There was a signing issue with the .VSI template last night. There will be an updated prop of the .VSI today to fix this.

    Sorry!

    Scott

  • Today .NET MVC requires an "Application" project. Will it support "Website" (compile on the fly) projects?

    Thanks

  • Hi Scott
    Like I wrote earlier my app goes down after upgrade to newer version of mvc.net. I don't know why my routes doesn't works. There is new version of System.Web.Routing.dll and with this assembly Default.aspx is not 'routed' to specified controller. Also I have problem with RedirectToAction within OnActionExecuting method.

    I giving up and now must revert my last changes to previous version. :(

  • Is anyone looking at how asynchronous calls to the model might be incorporated into a controller?

  • Scott, you are incredible, you wrote all those comments in 15 minutes.

  • Hi all, the bits were updated earlier today. So if you ran into problems with the download, try re-downloading the VSI. Sorry about that.

  • Hi Gabriel,

    >>>>>>> Thanks for the update Scott. I downloaded the source code, compiled and ran the templates .vsi file, created a new ASP.NET MVC web application with the new template under My Templates, and tried to run the new app. I get the following error: "Could not load file or assembly 'System.Web.Mvc' or one of its dependencies. Strong name signature could not be verified. The assembly may have been tampered with, or it was delay signed but not fully signed with the correct private key. (Exception from HRESULT: 0x80131045)".

    There was an issue with signing the .VSI Visual Studio template last night. We updated it today and if you download and run it again it should work now. Sorry for the inconvenience!

    Scott

  • Hi Andrew,

    >>>>>> Today .NET MVC requires an "Application" project. Will it support "Website" (compile on the fly) projects?

    Technically ASP.NET MVC supports both web-site and web application projects - although the VS project templates we ship are web application projects. The reason for this is because web application projects allow you to reference an assembly that contains all of the code - which allows for easy unit testing, whereas web site projects generate multiple assemblies.

    Note that Visual Web Developer Express 2008 will shortly support web application projects in addition to web site projects, so if your concern was that the ASP.NET MVC projects wouldn't work with VWD Express, that will shortly be no longer an issue.

    Hope this helps,

    Scott

  • Hi Piers,

    >>>>>>> Is anyone looking at how asynchronous calls to the model might be incorporated into a controller?

    Yes - that is something we are thinking about now. We don't have an ETA yet for when this feature will show up - but it is definitley something we are thinking about and trying to design in mind for.

    Thanks,

    Scott

  • Hi JPapp,

    >>>>>>>> One question. When calling RenderView(), it doesn't seem to set the ViewName in the result, which doesn't allow unit tests to verify the correct view was created. Is it enough to test that the result is the correct type and not null? I would think it would be a good idea to still test the view name to make sure it's not creating a different view.

    In general with unit tests you want to verify the behavior that you've caused to happen. So if you haven't explictly set the viewname it should be enough to verify that a RenderViewResult was returned. If you want to go further, you could check that the viewname property on the RenderViewResult is null - in which case the name will be the same as the action at runtime (by default this is what a null value for the name means with RenderViewResult).

    Hope this helps,

    Scott

  • Hi dario-g,

    Can you post what your RegisterRoutes() method looks like and what error you are seeing at runtime?

    Thanks,

    Scott

  • Hi Scott
    Thanks for the great article. I won't get time to look at the preview 3 until it is released. In the mean time, do you know if there is a fix for the problem where the "asp:DetailsView" element requires to be placed inside a form tag with a runat=server.
    Cheers

  • Hi Scott, thanks for the update.

    We have been looking to see if the new MVC framework can be used in a project that we are working on.

    One of the things that I can't seem to figure out is how to use more complex controls.
    Say I display a list of objects and I want to be able to select a group of them. Without the viewdata and post backs I can only get Ids from (a) hidden field(s). (Or at least this is all I have had time to come up with) Is there something that I am missing about retrieving selected objects rather than just an ID and having to reload from the model each time or is this not the purpose of MVC and I should be using web forms?

    Also, should the TempData be "cleaned out" with every other call when using redirectToAction? I was hoping that if you were using the redirect functionality, maybe three of four times depending on logical flow, building up of error messages to display, that the TempData would hold this, but it doesn't. I can see what you are doing by removing data held in the sessionstate if not needed and so on RenderView this would be viable, but when moving between redirects, should this not be persisted until a render is called?
    I have gotten round this for now by overridding and adding my own flag to say if redirecting and using the filters to persist once more.

    Am I missing the point and creating way too much work for myself?

  • Hi Scott,

    Sorry if I posted this twice...

    I have two questions about using mvc.net

    1. TempData - This clears anything out from a previous request. I guess that this is to clear the session state? This seems like a good idea. This also happens during Redirects. I would have thought that a redirect would keep all the TempData until you decide to finally render a view?? I ask this because if you call an action and want to build up a list of msgs (errors say), you could add a msg, then redirect to another view, if this view added another msg and you redirected once more, the initial entries in the TempData would be lost.
    I have implemented my own persistance by overriding the Redirect method, but it seemed like a hack to me. Is there a better was to do this?

    2. Complex controls - We are looking at using the frameowrk for a new project and whilst we realise that its still a preview and not even a RC, we are looking. One of the areas that I am having difficulty with is creating controls. We basically want two lists of objects and to be able to move objects between them. The lists will be paged. One from a datasource and one locally until the user decides to persist their choices. How can this be done? At the moment the only way I have found to do this is by storing the selected Ids in some hidden field and then reading them back from the form after submittion. I also have to keep persisting the selected objects in the TempData with each paging call on the other list. Is this a good way to do this or am I looking at this the wrong way? Should I be using web forms instead?

    Any input would be appreciated.

    Cheers
    Anthony

  • Two questions Scott:
    1. Will you plan on supporting both route capabilities going forward ?
    2. Will you plan on supporting void Actions going forward as well ?

  • Hi Scott
    Thanks for reply. My routes are basic and still the same acros mvc preview 1/2 and 3.

    RouteTable.Routes.Add(new Route("{controller}/{action}/{id}", new MvcRouteHandler())
    {
    Defaults = new RouteValueDictionary(new { action = "Index", id = (string)null })
    });
    RouteTable.Routes.Add(new Route("Default.aspx", new MvcRouteHandler())
    {
    Defaults = new RouteValueDictionary(new { controller = "Admin", action = "Index", id = (string)null })
    });

  • Scott,

    From a domain design stand point. How can I reuse my Controller Logic and Model Logic on a different View type (HTML vs. WinForm)?

    This is all great and wonderful and I love the product. I'm using it to build a Web Dashboard around some data collected with OSI/PI Software. What if I want to build a WPF or Silverlight 2.0 RIA or WinFrom would I be re-writing code or re-using binary logic? I started by separating the Control and Model logic into a separate assemblies (.dll). The referenced from a Windows From Project.

    The one drawback is with re-use for a different platform. The idea is that I could put business logic and other logic in the Controller. But now I can only use that Controller for an ASP.NET MVC View. How can I re-use the logic and enforce the same business rules but with a WPF View or a Windows Form View?

    I have multiple platforms to target and don't like to be pigeon holed into one type of Presentation. At the same time I don't like to re-write business logic because of the underpinnings (APS.NET). I would hate for an update to a controller go into one platform but not the other due to re-writing code and not re-using the changed assembly. I have to build many applications using many different frameworks to solve the same problem. Do I download SCSF. What about mobile devices?

    I understand that one of the challenges of accomplishing this is the two different technologies in application frame work between ASP.NET and a standard Windows From. The biggest being the disconnected client/server framework of ASP.NET and how something that works for that would not work for a local client event driven framework like WinForms. But It has been proven to work.

    I have been able accomplish using parts of this framework in a WinForm application. I just think if there was some additional seperation like a command mediator or something. Thin layer with one object that is sepefic to the implementation of asp.net. It would route the commands and work for asp.net and yet another one that would mediate and route the commands for an WinForm. Is there a way to seperate the underpinnings and give a nutuarl platform.

    I don't know I'm just thinking outlound, because I know there is a need to not re-write alot of code for an application that has two or more different Presentations.

  • Kind of a side comment here -- I LOVE the color scheme you use for the code snippets, black background is just so much more readable -- I don't know why so many people use a white background for text.

  • I am trying to use ASP.NET AJAX in sharepoint,I have use all the procedures i.e installing asp.net,editing the web.comfig and master page,but when ever I applied textbox auto-complete in sharepoint it did'nt work but it works on my local computer.Your help would be really appreciated

  • I had some success with your samples as well as others- The one thing I can't figure out is this:

    This project works fine when I run under the default, but when I add a virtual directory and try to run it from there on IIS I get an error-

    How/where to I make the mapping rule change?

    Runs fine like this- http://localhost/default.aspx but not like this- http://localhost/kigg/default.aspx

    When I click on a link- http://localhost/kigg/Story/Tag/General_Sciences/1 (error is file not found- I get a 404)

    I tried to make changer in the global.asax- but to no avail

    Do you know how to map controllers to a virtual directory? Can you give an example?


  • I really like the idea of the ActionResult although agree that naming conventions for RenderView, etc.. dont seem to fit.

    I have noticed the way the default routing has changed in this drop. When going to the root url Default.aspx is hit then does a Response.Redirect to the home controller. Im not fond of this as 1 for most sites the homepage would be the most requested and your forcing multiple requests each time. Also this is a 302 redirect and search engines handle them differently so could this be a concern? why move from the previous clean way of specifying a default controller / action?

  • Hi. Scott, there are two routing for searching in my project like you mentioned in the Url Routing post. One is the "Search" mapping to the "Index" action of "SearchController" and another is "Search/{query}" mapping to the "Result" action. The routing is correct but the problem is. Er, maybe it's really simple but I was confused for a long time. When I set the action attribute to "/Search/Result" of form tag in the view, then typed in some words in the textbox and click the submit button. Whatever and however I tried, I can't get a pretty url like "Search/keyword".

    How should the scenario be?

    Another problem is, if the keyword contain the dot or such as "%2f" etc, the application report an Not Found exception. How can I avoid this?

    Thank you very much, Scott.
    Have a good day!

  • Hi Scott
    I wrote to You couple days ago but I have another problem. In Application_Error event I have a lot of exceptions 'File not found':

    TargetSite: Void ProcessRequestInternal(System.Web.HttpContext)
    in System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context)
    in System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state)
    in System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
    in System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

    I'm doing something wrong or maybe there's a bug?

  • kudos for the team behind all this! I'm quite amazed to see Microsoft using opensource software (i.e moq)! I'm currently on a ruby on rails project, but can't wait to work with MVC ASP.NET

  • From where we can get the ASP.NET MVC framework to install?

  • Hi Scott,

    When I try to install the "Asp.Net MVC Templates" using the installer CodePlexMVCTemplates.vsi, I get error message shown below:
    " The content file you are trying to install has not been signed and might contain harmful code. Are you sure you want to install this content?
    To view the files that will be installed on your computer, click No and then click View files in Window Explorer. "

    Do I continue to install this? Will it harm to the existing .NET Framework?

    Regards,
    Gyan

  • is this the real MS? it's quite amazing to see all this cool stuff coming out of the ASP.NET team. even more amazing is a VP like Scott taking the time to answer and educate us about these new technologies. this is how to win the web. finally, i think someone at MSFT sees the big picture.

  • Yea thanks Scott for dropping us a line on all the great new technology

  • I just downloaded the VSI and the publickeytoken on the system.web.mvc.dll is still null, should this have been fixed in the second upload you performed?

  • I’m trying to use VB.NET to work with some AutoCAD and Excel files located in SharePoint folders.

    And not having any luck…I have spent days (literally) searching for some clue as to why I’m having this problem…

    Am I correct in thinking I need something on the SharePoint side, and the VB.NET side??

    Could you help me find a solution or someone who might be able to help, or a forum that you personally find knowledgeable and effective?

    Your assistance would be greatly appreciated! Thank you for your help!

    Pete
    naschkeps@pella.com

  • Scott,

    Can you please share a signed version of System.Web.Mvc.dll assembly (MVC 0416 Build)?

  • Hi Scott, I was messing around, trying to create custom controls with the MVC preview two and I seem to run into a lot of problems with embedded resources. I wonder if you could blog about this. It seems that by default, ClientScript.RegisterClientScriptResource requires a , which we don't need in MVC. I'm trying to use the GetWebResource URL but I get a 404 on the WebResource.axd file.

    Thanks a lot!

  • I am trying to use a simple MVC application working on IIS 6. I just created an MVC app using VS2008, compiled it and installed it on IIS server. When I click 'Home' or 'About' I am getting a 404 - 'Page not found' error.

    Also, I added a test page to website to display Environment.GetVersion. It is displaying the version as 2.0.50727.1433. I have installed 3.5 and 3.5 Preview-2 on the web server.

    I have also tried the NorthwindMVC sample, but am getting a different error (Could not load file or assembly 'System.Data.Entity, Version=3.5.0.0).

    Is there something obvious that I am missing. I have used ClassicASPs in the past, but am new to Asp.Net.

  • When someone give us trully informations about instaling mvc.net on IIS7?? Some configuration tips???

  • Everything looks fine the only problem with Returning ActionResult is that now if there is ne error while rendering UI/view/presentation error we'll get UGLY Yellow ASP.NET error Page. Earlier when we return void & use RenderView Method to render a view those error could be caught in try/catch block & we could have handle those.I am not sure what to do now?.ne idea folks

Comments have been disabled for this content.