Andy Evans
Andy Evans

Reputation: 7176

RouteConfig setup to accept an optional parameter

I am having problems setting up the RouteConfig file to accept an optional record ID as part of the URL like in the examples below.

http://localhost/123 (used while debugging locally)

or even

http://www.foobar.com/123 

Ideally, I would like to have the record ID (123 as in the examples above) be passed in as a parameter to the Index view of the Home controller. I had thought that the default routeconfig would suffice for this (using the ID as an optional element), but apparently the application is apparently trying to direct the browser to a view called '123' which obviously doesn't exist.

My current RouteConfig.cs looks like this:

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

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

Any assistance on this would be greatly appreciated.

Upvotes: 3

Views: 4003

Answers (2)

Mark
Mark

Reputation: 108567

Your routing says:

{controller}/{action}/{id}

that's your site then your controller, then your action and then an id.

You want just site then id:

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

This would then hit a controller at

public class DefaultController : Controller
{
    public ActionResult Index(int id)
    {
    }
}

Upvotes: 3

StriplingWarrior
StriplingWarrior

Reputation: 156708

"{controller}/{action}/{id}" tells MVC that a route may have a controller name, or it may have a controller name followed by an action name, or it may have those two followed by an ID. There's no way, given just an ID, for the routing to understand that it's supposed to be an ID and not an action or a controller name.

If you're never planning to have any other controllers or actions, something like this might work:

routes.MapRoute(
    name: "Default",
    url: "{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

But that's probably a bad idea. Pretty much every site has at least one key word to indicate what the ID represents. For example, StackOverflow has "/questions/{id}".

Upvotes: 1

Related Questions