Stan
Stan

Reputation: 26511

ASP.NET MVC3 Route - example.com/blog/projects to example.com/projects

I have an ActionResult in my Blog controller that is returning all the projects called Projects, but my URL looks like example.com/blog/projects, I want to set up route to make it look like example.com/projects.

Is it possible? And if it is then how can I achieve that?

Upvotes: 1

Views: 109

Answers (2)

akiller
akiller

Reputation: 2472

You can add a route to your Global.asax.cs file, such as:

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

So it looks something like this:

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

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

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

}

Make sure you put your new route above the default one otherwise yours will never be hit.

Upvotes: 2

dotnetstep
dotnetstep

Reputation: 17485

You have to register route following way Global.asax and put this as a first route

routes.MapRoute("Projects", "Projects" , new { controller="blog" , action="Projects" });

Upvotes: 2

Related Questions