2

Hello everyone :I am working on a .net mvc3 application. Here is my controller and action :

public class Foo_Bar : Controller
{
     public ViewResult Foo_Bar()        
    {

        return View();
    }
}

And my corespondent view file is : Foo_Bar.cshtml

now ,my question is : I have a url as: www.mystite.com/foo-bar/foo-bar but this url can not invoke the Foo_Bar/Foo_Bar controller and action except I write it as thes: www.mystite.com/foo_bar/foo_bar .

Now I need to replace the "-" with "_" before the route system mapping my controller and action. Can I do it in the routes.MapRoute()? Some one please help me .Thank you advance !ps:this is my first time to ask an question in Stack overflow:)

ssube
  • 41,733
  • 6
  • 90
  • 131
NextStep
  • 925
  • 3
  • 11
  • 18

2 Answers2

2

You can create a custom RouteHandler to change the values for {action} and {controller}. First, create your RouteHandler, as follows:

using System.Web.Mvc;  
using System.Web.Routing;  

public class MyRouteHandler : IRouteHandler  
{  
    public IHttpHandler GetHttpHandler(RequestContext requestContext)  
    {  
        var routeData = requestContext.RouteData;  
        var controller = routeData.Values["controller"].ToString(); 
        routeData.Values["controller"] = controller.Replace("-", "_");  
        var action = routeData.Values["action"].ToString();  
        routeData.Values["action"] = action.Replace("-", "_");  
        var handler = new MvcHandler(requestContext);  
        return handler;  
    }  
}  

Then, change your Default route as follows:

routes.Add("Default",  
    new Route("{controller}/{action}/{id}",  
        new RouteValueDictionary(  
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }),  
            new MyRouteHandler() 
        ) 
    );  
); 

When a request is satisfied by this route, the RouteHandler will change the dashes to underbars.

counsellorben
  • 10,704
  • 3
  • 37
  • 38
1

Use the attribute [ActionName]

public class Foo_Bar : Controller
{
     [ActionName("foo-bar")]
     public ViewResult Foo_Bar()        
    {

        return View();
    }
}

There isn't an equivalent for Controllers, so you can't use it in your route with {controller}. But you can define it explicitly at least.

Anders Marzi Tornblad
  • 17,122
  • 9
  • 50
  • 62
Daryl Teo
  • 4,921
  • 1
  • 25
  • 33