Controller responds to any user request for example when the user opens any URL in the browser or for any button click in Asp.Net MVC. Once Controller receives a request, it collaborates between Model & View and displays the output. The output of the Controller can be View, JSON object, XML, etc. Controller in Asp.Net MVC is a simple C# class which contains Action methods. Each browser request points to a Controller, and it responds to the request by calling an Action method. The Action method can simply return a View or anything else. For example, if user requests for /home/Reports, then HomeController named Controller responds to the request by calling Reports() action method. Reports() method can return a View or can return XML or it can redirect to another Controller or anything else.
Open Microsoft Visual Studio 2015 => Create Asp.Net MVC application. Add a new controller and name it as HomeController. Add Reports() method to Home controller as shown below.
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult Reports()
{
return View();
}
}
/home/Reports URL calls the above Reports() method.
In Asp.Net MVC, any Controller class inherits the base class Controller. Because of inheriting Controller class, many predefined action methods available for user defined Controller. The methods in the Controller class called as Controller actions.
The Controller Action methods can return any of the below results.
View: Action method can return simply View which contains HTML.
Partial View: It can return PartialViewResult which renders only some content of the view.
File: It can return any of the file content. For example, Action method can return PDF file content.
Redirect: Controller action method can return 302 status code. That means it can redirect to the new Controller temporarily. To redirect permanently action method should return status code 301.
Content: It just returns simple text.
JSON: Action method returns serializes an object which renders in JavaScript Object Notation(JSON) format.
JavaScript: It can just render JavaScript. For example action method can return javascript function like “function Display(){alert(‘This is from Asp.Net MVC’)}”.
HttpNotFound: Controller Action method can return HttpNotFoundResult which renders a 404 HTTP status code.
The action method can receive parameters from the request. For example, if Asp.Net MVC application receives a request from the browser as /Home/Reports/3, the request goes to a controller named HomeController. Inside the HomeController, it calls Action method Reports() by passing the parameter as “3”.
There are four different types of Controller templates available while adding controller from Microsoft Visual Studio.
Empty MVC controller
MVC controller with read/write actions and views, using Entity Framework
MVC controller with empty read/write actions
API controller templates