Ancient
Ancient

Reputation: 3057

Url routing with static name mvc

I have a controller name Dashboard and inside that controller i have an action AdminDashboard . Now by default url of this action becomes /Dashboard/AdminDashboard . I want to map this action to this url /SupervisorDashboard

This is what i am doing but its saying not found

routes.MapRoute(
            name: "SupervisorDashboard",
            url: "SupervisorDashboard",
            defaults: new { controller = "Dashboard", action = "AdminDashboard" }
        );

and also how can i redirect to this page using Url.Action

Global.asax

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "SupervisorDashboard",
            url: "SupervisorDashboard",
            defaults: new { controller = "Dashboard", action = "AdminDashboard" }
        );

    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

Upvotes: 0

Views: 2138

Answers (1)

Marian Polacek
Marian Polacek

Reputation: 2925

Have you placed this new route definition before default route? Routes are evaluated in the same order in which they were registered. If you put default route before any of custom routes, it will be used (and since you probably don't have any SupervisorDashboardController in code, 404 will be returned).

Url.Action should work correctly, if routes are defined in correct order.

So, for this case, RouteConfig should look like this:

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

        // this one match /SupervisorDashboard only
        routes.MapRoute(
            name: "SupervisorDashboard",
            url: "SupervisorDashboard",
            defaults: new { controller = "Dashboard", action = "AdminDashboard" }
        );

        // should be last, after any custom route definition
        routes.MapRoute(
          name: "Default",
          url: "{controller}/{action}/{id}",
          defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
      );
    }
} 

Upvotes: 2

Related Questions