Reputation: 4919
How to set the default controller in MVC4?
I've tried adding the below code to the Global.ascx but it said "Only assignment, call, increment, decrement, and new object expressions can be used as a statement", seems it can't find the "route", did I put it on the wrong place?
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
Below is the screenshot:
Upvotes: 3
Views: 3218
Reputation: 63065
you need to put this code inside RouteConfig.cs
under App_Start
.
check ASP.NET MVC 4: Where Have All The Global.asax Routes Gone?
Upvotes: 3
Reputation: 54377
The answers suggesting to use RouteConfig
are correct but a bit misleading. There's nothing magical about RouteConfig
; it's just a class that you create, name, and locate according to convention.
The important part is what you typically pass to RouteConfig
: RouteTable.Routes
The route table is available from anywhere within an ASP.Net application. For example, you could say:
protected void Application_Start()
{
RouteTable.Routes.MapRoute( "myroute", "apples", new { controller = "Foo", action = "Bar" } );
}
and it would work just fine. Of course, you should only initialize routes on startup and follow the convention of RouteConfig
for consistency.
But it's worth knowing why it works.
Upvotes: 1
Reputation: 14953
Take a look at App_Start/RouteConfig.cs file. This is where you will be able to configure routes in the way you want.
There, you will find code similar to this:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Upvotes: 3