Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve asp.net mvc action name with hyphen?

How to achieve asp.net mvc action name with hyphen e.g., www.domain.com/about-us where about-us is the acton name in home controller. With this approach, i can achieve to have the action name like contact-us, how-to, etc.

like image 443
Rajesh MG Avatar asked Sep 03 '13 07:09

Rajesh MG


1 Answers

Here's the complete working solution to the problem for a .Net MVC 5 project:

  1. Open your project's App_Start/RouteConfig.cs file.

  2. On your RegisterRoute method, modify the codes like this:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapMvcAttributeRoutes(); // <--- add this line to enable custom attribute routes
    
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
    
  3. Now, open your controller file then add your custom route's definition at the top your action as shown below:

    [Route("about-us")]
    public ActionResult AboutUs()
    {
        return View();
    }
    

You should now be able to use your custom route like this:

http://yourdomain.com/about-us
like image 182
Jhourlad Estrella Avatar answered Nov 04 '22 23:11

Jhourlad Estrella