ASP.NET MVC 3 Controller route - make everything under home controller appear under the domain

前端 未结 4 1247
你的背包
你的背包 2020-12-14 18:55

Currently everything under homecontroller appears in the URL as

example.com/Home/{Action}

Is there a way we can keep all other routing the

4条回答
  •  不知归路
    2020-12-14 19:45

    I think the best way is:

     routes.MapRoute("home", "home", new { controller = "Home", action = "Index" });
     routes.MapRoute("about", "about", new { controller = "Home", action = "About" });
     routes.MapRoute("contact", "contact", new { controller = "Home", action = "Contact" });
    
     routes.MapRoute(
         "Default", // Route name
         "{controller}/{action}/{id}", // URL with parameters
         new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
     );
    

    and when you want to create a link, use:

    @Html.RouteLink("Home", "home", new{/* route values */}, new {/* html attribues */})
    

    OR:

    @Html.RouteLink("Home", "home")
    

    instead of:

    @Html.ActionLink("Home", "Index", "Home", new{/* route values */}, new {/* html attribues */})
    

    this works for me, and should work for you too.

    UPDATE:

    you can create a symbol like @ (or - or anything else), before the action part in url, to make the url unique, such as:

    routes.MapRoute(
        "test",  // route name
        "@{action}", // url and parameters
        new {controller = "MyHome", action = "Home"} // parameter defaults
        );
    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
         );
    

    in this way, your urls are different from the Default map-route and you can create urls like:

    site.com/@Home
    site.com/@About
    site.com/@Contact
    

    but the first, in my idea, is better and I always use that.

提交回复
热议问题