3

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: enter image description here

4 Answers 4

3

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 }
            );
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

3

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?

Comments

1

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.

Comments

0

Please change it in your RouteConfig.cs file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.