0

I am writing a new MVC App; I want to make some changes to the routing to add department name to the URL.

The following is what is generated by VS 2012.

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

    routes.MapRoute( _
        name:="Default", _
        url:="{controller}/{action}/{id}", _
        defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
    )

I want to pass the department name in the beginning of the path. ex.

http: // localhost: /hr/Home/Contact

http: //localhost /hr/Home/About

http: //localhost /finance/Home/Contact

http: //localhost /finance/Home/About

http: //localhost /marketing/Home/Contact

http: //localhost /marketing/Home/About

Instead of the default pages:

http: //localhost /Home/About http: //localhost /Home/Contact

Community
  • 1
  • 1
user1621009
  • 81
  • 1
  • 1
  • 4

2 Answers2

1

That should be pretty straight forward; add department to the start of the route:

routes.MapRoute( _
    name:="DepartmentRoute", _
    url:="{department}/{controller}/{action}/{id}", _
    defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
)

You might want to also add a constraint to make sure it only matches department names:

    constraints:=New With { .department = @"[hr|finance|marketing]" }
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • Thanks for the quick response. How does I get the department name in my code? It uses the same code right? – user1621009 Aug 23 '12 at 21:43
  • @user1621009 yes, you can add it as a parameter to your action methods ... or retrieve it straight from the Route Values object. DarthVader's suggestion is also a good one to consider. – McGarnagle Aug 23 '12 at 22:15
  • Thanks for such a quick response. I think you solved my problem. – user1621009 Aug 23 '12 at 23:50
0

There are two ways to access the department name once you have it in the URL. One way is to use the property RouteData.Values like this:

string department = RouteData.Values["department"];

The other way is more elegant. If we define parameters to our action method with names that match the URL pattern variables, the MVC Framework will pass the values obtained from the URL as parameters to the action method.

   public ViewResult Index(string department) {
      ViewBag.Department = department;
      return View();
   }
Flavia Obreja
  • 1,227
  • 7
  • 13