Thursday, 5 December 2013

How to set a particular page as Startup page in MVC project?


Today I am going to explain how to set a particular page as Startup page in MVC project.

In normal three tier architecture we will select an aspx page in the solution explorer. Then right click on the page and select set as start page in the menu items.

But in an MVC project we cannot set a page as set as start page.

In order to set that page as a startup page we need to write the code in Global.asax page.

Go to global.asax.cs page.

Create a method called Application_Start() and write the following code

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
Now in RegisterRoutes method add the path info to the page.
public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );


Now give the route map.

When we run a page in MVC it will first call the controller from there it returns to the view.

So here also we will call the controller first and then the controller calls the corresponding view.

So in controllers write the name of the default controller and in views write the name of the view which you want to show as startup page.

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "ControllerName", action = "CorrespondingViewName", id = UrlParameter.Optional }
            );
Now we’ll have a look at the entire code.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

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

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

No comments:

Post a Comment