Search code examples
asp.net-mvcroutesasp.net-mvc-routing

Page Routing with Partial View & Custom URL's


I have custom route to add a slug to the end of my Urls that contain and Id for SEO purposes.

I am wanting to be able to have SEO friendly url's, which look like this:

http://localhost:12345/OurWork/Project/26/MortgageBancLLC

I have achieved this for the Project/ page but the other pages blow up. I use a partial view to display my latest projects on the other pages. This partial view displays the last three projects on the home, services, about, etc... pages.

I've tried to reorder the order in which my routes are listed, but it only partly works. If I reverse the order of the routes, then the pages load but then my url change to this:

http://localhost:12345/OurWork/Project/26?slug=CompanyNameHere

Here are my routes:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

                //This is my SEO friendly route
                routes.MapRoute(
                    "SeoFriendlyRoute", 
                    "{controller}/{action}/{id}/{slug}",
                    new { controller = "OurWork", action = "Project", id = UrlParameter.Optional, slug = UrlParameter.Optional }
                );

Here is a link where I am passing my id and the slug:

<a href="@Url.Action("Project", "OurWork", new {id = item.Project.Id, slug = @item.Client.Name })">CompanyName</a>

My guess is I need to add another route, but I'm not sure how to handle this when the Home page uses one route and the partial view will use another.

Please advise. Thanks


Solution

  • You do not need the 2nd route, "SeoFriendlyRoute". Just change the first route to include the slug at the end of the url and make the slug optional. That way if you are on the home page or any other page that does not require a slug, it will work.

    You can leave the controller as "home" and the action as "Index".

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