Lord of Scripts
Lord of Scripts

Reputation: 3619

How to define a route with two parameters in this situation?

I am using ASP.NET MVC3 with Razor and would like to define a route that would allow me to receive URLs such as this. Note I am new at MVC3:

/State/Florida/Town/Fort_Lauderdale
/State/Texas/Town/Irvine
/State/Alabama/Town/Auburn

I would like that to be handled by the existing "States" controller (StatesController class) using the "Town" action. I have something like this:

routes.MapRoute(
   "Towns",
   "{controller}/{state}/{action}/{town}",
   new { controller = "States", action = "Town", state= UrlParameter.Optional, town = UrlParameter.Optional }

Obviously neither the state nor the town parameters are optional, how do I go about that? I don't think the above route is correct, isn't there a way to indicate that the parameter is NOT optional?.

Another situation here is that while with the above I pretended to handle the towns with a single action in a controller Town(string town), I would still need to be able to parse individual town files with Razor. I originally thought of having the Town() controller method to use the town parameter to serve a town's HTML file but as it turns out, I also want to be able to have dynamic data on a town description. Does that means that my best solution is to create a dedicated Town controller and create one action method for each of the MANY towns?

Any suggestions to better handle that?

Upvotes: 0

Views: 400

Answers (1)

Ivo
Ivo

Reputation: 8372

Just remove the UrlParameter.Optional

routes.MapRoute(
    "Towns",
    "{controller}/{state}/{action}/{town}",
    new { controller = "States", action = "Town" }

I would just go for something more explicit like:

routes.MapRoute(
    "Towns",
    "State/{state}/Town/{town}",
    new { controller = "States", action = "Town" }

Indeed, there's a typo in the previous one (based on the one you posted) because the controller is States by default and State by the url.

Upvotes: 1

Related Questions