Search code examples
sitecoresitecore-mvc

Sitecore - Adding route in Application_Start


I am using sitecore 7.5 and I need to add new route in application_start in order to use it in ajax call but when I run the application it seems that sitecore deals with the route as content item any help please


Solution

  • Here is the code that creates a route for you. In global.asax.cs you will call RegisterRoutes from App_Start event handler:

        protected void Application_Start()
        {
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    

    And there you specify your route as:

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute(
                 name: "test",
                 url: "mvc/Forms/{action}/{id}",
                 defaults: new { controller = "Forms", action = "Test", id = UrlParameter.Optional }
               );
        }
    

    You will have /mvc/ prefix in this case that will handle your route to specifies controller, so you will call it as:

    /mvc/Forms/Test/{you_may_pass_some_optional_GUID_here}
    

    This will route to FormsController class action method Test(string id) but you may omit id parameter

    A bit of attention: Please note that setting route in Application_Start is not the best way of doing that; much better is to implement mapping routes at Initialize pipeline, as it fits Sitecore architecture:

    public class Initialize
    {
        public void Process(PipelineArgs args)
        {
            MapRoutes();
        }
    
        private void MapRoutes()
        {
            RouteTable.Routes.MapRoute(
                    "Forms.Test", 
                    "forms/test", 
                    new
                    {
                        controller = "FormsController",
                        action = "Test"
                    },
                    new[] { "Forms.Controller.Namespace" });
         }
    }
    

    The rest of implementation: Also I have previously wrote an article in my blog about how to implement ajax call to a route, that will guide you through the rest of the implementation process:

    http://blog.martinmiles.net/post/editing-content-on-a-cd-server

    Update: Please also make sure your config has a handler to handle your prefix, see below:

    <customHandlers>
        <handler trigger="~/mvc/" handler="sitecore_mvc.ashx" />