ASP. net mvc source refresh Preview

Source: Internet
Author: User
Tags http redirect
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 removed Ded 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 notAn 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 hassystemic-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.

Improvements with this ASP. net mvc source refresh

This week's update (which you can download here) includes des 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 wrongly ded 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 abve it in the main project templates section of the dialog ). this allows you to safely create new projects 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 wowould 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 CILS).

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 cocould 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 mechanic 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 wocould be easy to create a "renderfile ()" helper method, for example, that a developer writing an action cocould 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 abve 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 refreshing 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 your times as you want to register multiple named routes in the system. for example, in addition to the default convention rule, we cocould 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 cocould 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 wowould then access the routing system and output an appropriate HTML hyperlink URL like below (note: how it did automatic IC 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 abve 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 wocould 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 wocould 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 wocould 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 ineffecate 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.