How to: Add a Controller to an MVC Application in Visual Studio
Introduction
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 only one controller, which is named HomeController.
This topic shows how to add a new controller to an existing MVC application.
To add a controller to an MVC application
-
Open the MVC application in Visual Studio.
-
In Solution Explorer, right-click the Controllers folder, click Add, and then click New Item.
The Add New Item dialog box is displayed.
-
Under Categories, expand either Visual Basic or Visual C# (depending on your project), expand Web, and then click MVC.
-
Under Templates, select MVC Controller Class.
-
In the Name box, type the name of the controller, using "Controller" as a suffix.
Note
The ASP.NET MVC framework requires controller names to end with "Controller", such as HomeController, GameController, or LoginController.
-
Click Add.
Visual Studio adds the controller class to the project.
Example
When Visual Studio generates the new controller, it includes an action-method stub. The following example shows a newly generated controller class.
Public Class ProductController
Inherits Controller
Public Function Index()
' Add action logic here
Throw New NotImplementedException()
End Function
End Class
public class ProductController : Controller
{
public ActionResult Index()
{
// Add action logic here
throw new NotImplementedException();
}
}
This topic is ASP.NET Extensions documentation and is unsupported by Microsoft. Blank topics are included as placeholders and existing content is subject to change in future releases.