0

How can I do route configuration as below?

My current url is: http://localhost:4815/Home/ByCategory/1

But I want it to be: http://localhost:4815/CategoryTitle

public ActionResult ByCategory(int? id)
{
    ...
}

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "ByCategory", id = UrlParameter.Optional }
        );
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • I'm unclear about what this question is asking. Do you want to add another action to your controller, but an action that doesn't require an 'id' parameter? – Chris HG Feb 08 '20 at 18:34
  • When I click on the link, I don't want it to be http: // localhost: 4815 / Home / ByCategory / 1. I want to http: // localhost: 4815 / CategoryTittle – Engin Ozsozgun Feb 08 '20 at 18:40

3 Answers3

1

You can use Attribute Routing. for doing this at first you must Enable it by adding below code top of your MapRoute in RouteConfig:

routes.MapMvcAttributeRoutes(); //Enables Attribute Routing

then you can add Attribute Routing at top of your classes and methods:

 [Route("CategoryTitle")]
 public ActionResult ByCategory(int? id)
        {
           ...
        }

for deep dive in Routing, you can follow this link.

good luck.

Hamed Moghadasi
  • 1,523
  • 2
  • 16
  • 34
0

If you want to parametrize a route with Category Title, you can use Attribute Routing like so

[Route("~/{categoryTitle}")]
public ActionResult ByCategory(string categoryTitle)
...
Pavel Shastov
  • 2,657
  • 1
  • 18
  • 26
0

Thank you for your suggestions. I have added the following code to routeconfig. I used <a href="/question"> </a> on the view page to go to the relevant controller

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.MapRoute(
               name: "AddQuestion",
               url: "AddQuestion",
               defaults: new { controller = "Question", action = "Create" }
           );