1

I am using C# MVC.

I have an action which looks like this.

    public class CustomController : Controller
    {
        public ActionResult CustomPage(int customPageId)
        {
            var model = new CustomPageViewModel()
            {
                customPageId = customPageId
            };

            return View(model);
        }
    }

I want to be able to hit this action but to use a different route. For example I want Home/Index to actually hit this action, but to report in the URL that its Home/Index.

My custom pages are stored in the database which tell it what route to have, how can I create routes for my pages programatically and have MVC perform the required actions?

As this is a CMS based system, I don't want to have to create a Home/Index controller and action, as the user may choose any route they wish.

Thanks, Tom

1 Answers1

0

FYI: I have sort of figured this out. Unfortunately Routes are defined when the application starts, so I have to force a restart if I want to setup a new route while the app is running...

Here is the code I have used to setup my routes incase it helps anybody else.

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

        var pageList = new PageService().Get();

        foreach (var page in pageList)
        {
            var targetRoute = string.Format("{1}/{2}", page.PageArea, page.PageController, page.PageAction);

            if (!string.IsNullOrWhiteSpace(page.PageArea))
                targetRoute = string.Format("{0}/{1}/{2}", page.PageArea, page.PageController, page.PageAction);

            routes.MapRoute(
                string.Format("PageBuilder_{0}", page.PageId),
                targetRoute,
                new { area = "Builder", controller = "Build", action = "Index", pageId = page.PageId }
            );
        }

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
  • 1
    A better idea is to use one or more [data-driven routes](http://stackoverflow.com/a/31958586/181087) rather than modifying the route collection at runtime. – NightOwl888 Jul 08 '16 at 22:25