12

In the MVC default route

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

whenever the index action is accessed, the url is not showing the action name when the "Index" action is accessed.

I would like to get that behaviour on a different controller, which is retrieving data for a single item. I would like the default action to be named "get" and for this action I would like the url not to display the action name, just the controller and the item id.

I thought that a similar route to the one above, like this:

routes.MapRoute(
            "item_details",
            "item/{action}/{id}",
            new { controller = "item", action = "Get" }
            );

would do the trick, but it gives me a url like localhost:xxxx/item/Get/152... What am I missing?

3 Answers 3

16

Try this:

routes.MapRoute(
        "item_details",
        "item/{id}",
        new { controller = "item", action = "Get" }
        );
4
  • Done. Sorry, meant to do it yesterday, but with the minimum time imposed by SO I went home before I got to do it ;o)
    – yu_ominae
    Commented Jan 24, 2012 at 7:28
  • @robasta what if item is the name of my controller and I only want to hide specific action Commented Aug 13, 2016 at 5:22
  • how to hide controller name from route? any idea? Commented Dec 28, 2016 at 10:14
  • @robasta Why I get Not Found error if I type item/Get/25 where id = 25? Anyway to let the route to accept with and without the action name, Get?
    – sky91
    Commented Feb 27, 2017 at 9:57
0

Try this:

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

For the users coming here as in ASP.NET MVC 5.2 days, it works when
you have id = UrlParameter.Optional added, at least for my case

 routes.MapRoute(
          name: "item_details",
          url: "item/{id}",
          defaults: new { controller = "item", action = "Get", id = UrlParameter.Optional }
        );

And if there are more routes in RouteConfig class, then move this to the top of other routes
or
You can also do:

routes.MapRoute(
               name: "item_details",
               url: "item",
               defaults: new { controller = "item", action = "Get", id = UrlParameter.Optional }
            );

Ref: this SO answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.