Search code examples
c#asp.net-mvc.net-coreroutesslug

if landing page has slug, make links from that landing page contain slug


I am using slugs to change the theme of the landing page for users. If they start their journey on a landing page that has the slug appended to the URL, I want to make sure all the links on that page will go to their slug equivalent.

Here is my RouteConfig:

public static void RegisterRoutes(RouteCollection routes)
        {
        
            routes.MapRoute(
                name: "SignUpJourney",
                url: "SignUp/{signUpJourney}/{slug}/{action}",
                defaults: new { controller = SignUpController.ControllerName, action = SignUpController.IndexAction, slug = UrlParameter.Optional, signUpJourney = UrlParameter.Optional },
                namespaces: new[] { "MyApp.Controllers" },
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{slug}",
                defaults: new { controller = HomeController.ControllerName, action = HomeController.IndexAction, slug= UrlParameter.Optional },
                namespaces: new[] { "MyApp.Controllers" }
            );
        }

When I manually type in the slug at the end of the URL, the page takes me to the correct themed landing page depending on the slug, but the links on that page (e.g. Login) link route me back to the default, unstyled login page. Is there a way in MVC to add the slug to any links that begin from a journey that has a slug? I'm struggling to find articles and/or best practices on this but I'm also fairly new with asp.net-mvc.

Thanks


Solution

  • You could check the current request contains your given slug and then based on that set the desired URL.

    if (Context.Request.QueryString.Value.Contains("your-slug"))
    {
            @Html.ActionLink("Link Test", "ActionName", "ControllerName", new { slug = 'your-slug' })
    } else 
    {
        @Html.ActionLink("Link Test", "ActionName", "ControllerName")
    }