Export (0) Print
Expand All

How to: Add a Controller to an MVC Application in Visual Studio

In an ASP.NET MVC application, a controller is a class that processes incoming requests, handles user interactions, and executes appropriate application logic. An MVC controller class is derived from the Controller class, which provides methods for rendering a view and for switching between controller actions.

An MVC application can have any number of controllers. The MVC application that is generated when you start a new project has two controllers, which are named HomeController and AccountController.

This topic shows how to add a new controller to an existing MVC application.

To add a controller

  1. In Visual Studio, open the MVC application.

  2. In Solution Explorer, right-click the Controllers folder, click Add, and then click Controller.

    The Add Controller dialog box is displayed.

    Dd410057.MVC_AddControllerDialog(en-us,VS.100).png
  3. In the Name box, type the name of the controller, using "Controller" as a suffix.

    The ASP.NET MVC framework requires controller names to end with "Controller", such as HomeController, GameController, or LoginController.

  4. If you want the new controller to contain action methods for data-handling scenarios, select the Add action methods for Create, Update, and Details scenarios check box. Otherwise, clear the check box.

  5. Click Add.

    Visual Studio adds the controller class to the project.

When you use the Add Controller dialog box and select the Add action methods for Create, Update, and Details scenarios check box, Visual Studio generates the new controller with action methods for views to display and edit data. The following example shows a controller class that was generated with the check box selected.

public class ProductController : Controller
{
    //
    // GET: /Products/

    public ActionResult Index()
    {
        // Add action logic here
        return View();
    }

    //
    // GET: /Products/Details/5

    public ActionResult Details(int id)
    {
        return View();

    }

    //
    // GET: /Products/Create

    public ActionResult Create()
    {
        return View();
    } 

    //
    // POST: /Products/Create

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(FormCollection collection)
    {
        try
        {
            // TODO: Add insert logic here

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

    //
    // GET: /Products/Edit/5

    public ActionResult Edit(int id)
    {
        return View();
    }

    //
    // POST: /Products/Edit/5

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, FormCollection collection)
    {
        try
        {
            // TODO: Add update logic here

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
}

Show:
© 2014 Microsoft