How can I create a friendly URL in ASP.NET MVC?

22,925

Solution 1

There are two steps to solve this problem. First, create a new route or change the default route to accept an additional parameter:

routes.MapRoute(  "Default", // Route name
                   "{controller}/{action}/{id}/{ignoreThisBit}", 
                   new { controller = "Home", 
                         action = "Index", 
                         id = "",
                         ignoreThisBit = ""}  // Parameter defaults )

Now you can type whatever you want to at the end of your URI and the application will ignore it.

When you render the links, you need to add the "friendly" text:

<%= Html.ActionLink("Link text", "ActionName", "ControllerName",
                    new { id = 1234, ignoreThisBit="friendly-text-here" });

Solution 2

This is how I have implemented the slug URL on my application. Note: The default Maproute should not be changed and also the routes are processed in the order in which they're added to the route list.

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home",
          action = "Index",
          id = UrlParameter.Optional
    } // Parameter defaults
);
routes.MapRoute("Place", "{controller}/{action}/{id}/{slug}", new { controller = "Place", action = "Details", id = UrlParameter.Optional,slug="" });

Solution 3

you have a route on the global.asax

  routes.MapRoute(
                    "Default", // Route name
                    "{controller}/{action}/{id}", // URL with parameters
                    new { controller = "Home", action = "Index", id = ""} 
                    // Parameter defaults )

you can define your own route like :

controller is the cs class inside the the controllers folder.

you can define your id - with the name you choose.

the system will pass the value to your actionResult method.

you can read more about this step here : http://www.asp.net/learn/mvc/tutorial-05-cs.aspx

Share:
22,925
Kieron
Author by

Kieron

Kieron works as a Technical Lead in the south of England, UK. He loves coding, gaming, gadgets and BBQ.

Updated on March 08, 2020

Comments