通过Global.asax.cs的MVC路由没有达到模型

时间:2014-10-08 20:13:41

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-5

我正试图路由到我的控制器,我无法弄清楚我做错了什么,这让我感到恼火。

的Global.asax.cs

 protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
    void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(
            name: "Default",
            url: "Groups/{0}/{1}",
            defaults: new
            {
                controller = "GroupSections",
                action = "Details",
                groupName = "",
                sectionName = ""
            }
        );

控制器

  public ActionResult Details(string groupName, string sectionName)
    {
        //code
    }

2 个答案:

答案 0 :(得分:2)

如果您看到this route examples,则您的路线应为:

 routes.MapRoute(
        name: "Default",
        url: "Groups/{groupName}/{sectionName}",
        defaults: new
        {
            controller = "GroupSections",
            action = "Details",
            groupName = "",
            sectionName = ""
        }

答案 1 :(得分:0)

void RegisterRoutes(RouteCollection routes)不应该在你的asax中,它应该在你的RouteConfig静态类中。

RouteConfig.cs

public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        //your route config.
    }
}

编辑:另外,如Brian Mains回答中所述,您的路线应该类似于:

routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });

括号中的名称映射到默认对象中的值。