The following directions will create both a custome MVC route and show how you can return something other than a View.
- Adding a custom route
- Open up the ASP.NET MVC VS.NET project.
- Open up the Global.asax file.
- Add the following code, right above the default routing code:
routes.Add( "DotNetFun", "DotNetFun/{GUID}", new { controller = "DotNetFun", action = "Article" } ); - 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.
- In the Solution Explorer, right click on the Controllers folder, then click on Add-->Controller.
- Name the controller DotNetFunController.
- Click on Add.
- 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. - Save the file.
- Right click inside of the Article method, then click on Add View...
- Leave the defaults, then click on Add.
- Press Ctrl-Shift-B to compile your project, then click on Ctrl-F5 to test it.
- You should be able to get to the related path like this: http://localhost:????/DotNetFun/8599AE31-2409-4875-9ECF-0698FAE23EDA
- 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 - Returning content other than a View
- 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()); } - Recompile the application.
- 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:
Post a Comment