Search code examples
asp.net-mvcasp.net-mvc-4asp.net-mvc-routing

MVC advanced routing using hyphenated parameters


I have a NEWS and a CARS section in my MVC 5 website and I so far have defined the following routing for News;

//route to cheat routing engine to generate id-slug
routes.MapRoute("NewsForReal", "news/{idandslug}", new { controller = "News", action = "Show" });
routes.MapRoute("News", "news/{id}-{slug}", new { Controller = "News", action = "Show" });

This works due to the following code in my NewsController.cs file which splits/concatenates the parameters for the routing above;

public ActionResult Show(string idandslug)
    {
        var parts = SeperateIDandSlug(idandslug);
        if (parts == null)
            return HttpNotFound();

        var news = Database.Session.Load<News>(parts.Item1);
        if (news == null || news.IsDeleted)
            return HttpNotFound();

        //redirect urls using correct slug if incorrect - SEO broken URLs
        if (!news.Slug.Equals(parts.Item2, StringComparison.CurrentCultureIgnoreCase))
            return RedirectToRoutePermanent("Post", new { id = parts.Item1, slug = news.Slug });

        return View(new NewsShow
        {
            News = news
        });

    }

    private Tuple<int, string> SeperateIDandSlug(string idandslug)
    {
        var matches = Regex.Match(idandslug, @"^(\d+)\-(.*)?$");
        if (!matches.Success)
            return null;

        var id = int.Parse(matches.Result("$1"));
        var slug = matches.Result("$2");
        return Tuple.Create(id, slug);
    }

I also want to use a similar format for the cars section where the first value is always the entity ID:

"/carsforsale/15489-ford-fiesta-2009-petrol-manual-black"

Can I do this by duplicating and updating my SeperateIDandSlug function, and then add more parameters that are required to build the URL? Or Can I get the job done by just using constraints?

Thanks in advance for any help!


Solution

  • routes.MapRoute("Cars", "cars/{id}-{make}-{model}-{year}-{fueltype}-{transmission}-{colour}", new { controller = "Cars", action = "Detail" }, new { id = @"(\d+)" }); 
    
    routes.MapRoute("News", "news/{id}-{slug}", new { controller = "News", action = "Show" }, new { id = @"(\d+)" });
    

    Above Code worked for me!