Tuesday, March 24, 2009

ASP.NET MVC - Creating Routing Constraints

To restrict the format of the parameter passed to an action method, you can create a custom route with a regular expression to determine in what format you want the parameter.

  1. Open up the Global.asax file.
  2. Add the following routing code, right above the default route: routes.MapRoute( "Test1", "Test1/{AreaCode}", new { controller = "Test1", action = "Index" }, new { AreaCode = @"[1-9][0-9][0-9]" } );
  3. Save the file and compile (Ctrl-Shift-B) and load the application (Ctrl-F5).

The controller action method (in the Test1Controller.cs class file) for the preceding route should look something like this (provided a View was created for that action result:

public ActionResult Index(int AreaCode) { return View(); }

Test1 refers to the controller, Index refers to the action, or method, and {AreaCode} refers to the parameter passed to that action/method. When it runs, MVC calls the following method: Test1Controller.Index(AreaCode). The "[1-9][0-9][0-9]" regular expression ensures that the parameter passed contain 3 digits, no more, no less. If the constraint is violated, a "The resource cannot be found." error code is returned.

The following URL is valid for the preceding example: http://localhost:????/Test1/111

The following URLs are NOT valid for the preceding example:
http://localhost:????/Test1/11x
http://localhost:????/Test1/11
http://localhost:????/Test1/1123

No comments: