Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

Default Routes not redirecting to expected page in mvc

I have a HomeController in which I have 2 ActionResults say Index and Projects. Now my RouteConfig.cs has below routes added:

routes.MapRoute(
    name: "Default_1",//Changed this to some other name
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
    name: "Default",//Made this name as Default
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Projects", id = UrlParameter.Optional }
);

So from the above configuration I was expecting by the default the user will redirected to /Home/Projects. But again it is redirecting to Index action. Why it is not redirecting to Projects action? Can't we have multiple routes here?Default name will not be considered as default url?

Upvotes: 0

Views: 108

Answers (1)

Shyju
Shyju

Reputation: 218722

When you register your routes,put your specific route definition(s) before the default route definition. The order of route registration matters.

routes.MapRoute(
    name: "Project",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Projects", id = UrlParameter.Optional }
);    

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

With this configuration, Any requests coming will be redirected to your Home/Projects because the url pattern is still the generic pattern({controller}/{action}/{id}). So i guess you really meant something like this.

routes.MapRoute(
    name: "Project",
    url: "projects/{id}",
    defaults: new { controller = "Home", action = "Projects", id = UrlParameter.Optional }
);    

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

This will send the request http://yourSite.com/Projects to Home/Projects

Or you may use attribute routing to define this route pattern in the Projects controller.To enable attribute routing, you can call the MapMvcAttributeRoutes method in the RegisterRoutes method of RouteConfig.cs. You will still keep the default route definition there.

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

    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

    );
}

And in your ProjectsController

[Route("Projects/{id?}")]
public ActionResult Index(int? id)
{
   //check id value  and return something
}

Upvotes: 2

Related Questions