Monday, March 23, 2009

ASP.NET MVC - Creating Custom Routes

The following directions will create both a custome MVC route and show how you can return something other than a View.

  1. Adding a custom route
  2. Open up the ASP.NET MVC VS.NET project.
  3. Open up the Global.asax file.
  4. Add the following code, right above the default routing code: routes.Add( "DotNetFun", "DotNetFun/{GUID}", new { controller = "DotNetFun", action = "Article" } );
  5. In the preceding route, DotNetFun refers to the controller, Article refers to the action method, and {GUID} refers to the parameter passed to the method, in the form of a valid Guid.
  6. In the Solution Explorer, right click on the Controllers folder, then click on Add-->Controller.
  7. Name the controller DotNetFunController.
  8. Click on Add.
  9. Modify the existing Index method so that it looks like the following: public String Article(Guid GUID) { return GUID.ToString(); }Notice how the name of the method changes completely.
  10. Save the file.
  11. Right click inside of the Article method, then click on Add View...
  12. Leave the defaults, then click on Add.
  13. Press Ctrl-Shift-B to compile your project, then click on Ctrl-F5 to test it.
  14. You should be able to get to the related path like this: http://localhost:????/DotNetFun/8599AE31-2409-4875-9ECF-0698FAE23EDA
  15. Again, DotNetFun refers to the controller and 8599AE31-2409-4875-9ECF-0698FAE23EDA to the Guid value passed as a parameter to that method. We don't need to add Article to the URL, since the controller is mapped to it already. We could always demand it by modifying the route, like this: routes.MapRoute( "DotNetFun", "DotNetFun/{action}/{GUID}", new { controller = "DotNetFun", action = "Article" } );Then, we could use the following URL: http://localhost:????/DotNetFun/Article/8599AE31-2409-4875-9ECF-0698FAE23EDA
  16. Returning content other than a View
  17. By default MVC returns a View, which is typically in the form of an ASPX web form, but you can return a string, too. To do this, for example, modify the preceding DotNetFun controller action created above: public String Article(Guid GUID) { return String.Format("You passed to the Article method this GUID: {0}", GUID.ToString()); }
  18. Recompile the application.
  19. The result should reveal something like this: You passed to the Article method this GUID: 8599ae31-2409-4875-9ecf-0698fae23eda

Please note that if the parameter passed is not a valid Guid, you'll get the following error:

The parameters dictionary contains a null entry for parameter 'GUID' of non-nullable type 'System.Guid' for method 'System.String Article(System.Guid)' in 'MVCTest.Controllers.DotNetFunController'. To make a parameter optional its type should be either a reference type or a Nullable type. Parameter name: parameters

No comments: