Naveed Butt
Naveed Butt

Reputation: 2901

Id in the beginning of the Route in MVC

I have a situation where I want a route in my application so that the application's index method can recognize this http://www.website.com/ID

and also, http://www.website.com/Controller/Action should also work.

The problem is that, when I set up the route corresponding to the first URL, the route for the second URL does not work (even if I set up a separate route for that).

Please tell me what am I doing wrong here...

Upvotes: 1

Views: 156

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

The following should work:

routes.MapRoute(
    "DefaultWithID",
    "{id}",
    new { controller = "Home", action = "Index" }
);

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

Assuming:

public class HomeController : Controller
{
    public ActionResult Index(string id)
    {
        return View();
    }
}

Both: /123 and /Home/Index/123 work fine.

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532765

Does the ID value have some distinguishing characteristic that would allow you to tell the difference between it and a controller name? For example, is it numeric? If so, you can set up a constraint on the first route so that it only matches ids. This would allow other requests to fall through to the second (default) route.

routes.MapRoute(
    "IdRoute",
    "{id}",
    new { controller = "home", action = "get" },
    new { id = "\d+" } // match ids that consist of 1 or more digits
);

routes.MapRoute(
    "Default",
    new { controller = "home", action = "index", id = UrlParameter.Optional }
);

Upvotes: 2

Related Questions