How To Add ASP.NET MVC to a Web Form Application

1 minute read

ASP.NET MVC is very popular now a day. But we have much legacy system of ASP.NET web form. If you want to use ASP.NET MVC with legacy ASP.NET web form application. What should you do? This is not encouraged to create an application with ASP.NET web form and ASP.NET MVC together. If you need, you can use. So, let’s start. In this application I used Visual Studio 2012 and .NET framework 4.5

Step 1: Create a ASP.NET Web Forms Application

  • Open visual studio, Got to File->New->Project
  • Select Template -> Visual C# -> Web -> ASP.NET Web Forms application, set location and click OK

Step 2: Add Reference

  • Click right button on the project -> Add Reference ->Extensions -> System.web.mvc
  • And Add Reference -> Framework -> System.Web.Routing

Step 3: Configure Default Routing
Modify the Application_Start method of Global.asax file. Write down the following code snippet in the Application_Start method .

System.Web.Routing.RouteTable.Routes.MapRoute("Default", "{controller}/{action}/{id}",
                new { Controller = "Home", action = "index", id = "" });

Here Route name is Default and default routing is {controller}/{action}/{id} . Here, default controller is Home and default action is index and default id is empty.

Step 4: Create Controller directory and Controller

  • Create a controller directory by right click on solution ->Add -> New folder -> Controllers
  • Create a controller by right click on Controller folder -> Add -> Class -> MyController (name of the class)
  • And create an action in MyController - name AboutMe like below.

MyController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace WebFormMVC.Controllers
{
    public class MyController : Controller
    {
        public JsonResult AboutMe()
        {
            return Json(new { name = "Mahedee Hasan", designation = "Software Architect"}, JsonRequestBehavior.AllowGet);
        }
    }
}

Now run the application, if you set default page of your application is default.aspx. You will see the output of as usual asp.net webform application. Now change the URL like : http://localhost:53598/My/Aboutme you will see a json output. This is actually MVC output.

If you are not clear in any portion or you have any suggestion, please leave your comment here. To run the application you may require some packages to download.