Skip to main content

MVC Controller

Controller is a class that defines execution flow in MVC application.Controller receives request from browser, it calls the model and perform business logic then it calls the view to render output on UI.
It is recommended to create controller class as public class.Controller class should inherit from System.Web.MVC.Controller base class
This base class provides necessary predefined methods for each controller such as View(), Redirect(), Content() etc.
Controller name should have suffix ‘Controller’.
For example you want to create a controller Home so it must be named as “HomeController”.
If you want to create a controller for Products so it must be named as “ProductController”.If it does not have suffix ‘Controller’, MVC framework will not identify it as Controller class so it can not receive any request.

Below is the syntax for declaring controller class:

public class CustomerController: System.Web.MVC.Controller
{

}

Execution Flow

The execution flow is :
Browser sends request to web server then web server forwards request to ASP.Net MVC framework. ASP.Net MVC framework identifies the appropriate controller and invokes the controller. Controller invokes service model which contains business logic, controller invokes required methods of service model to process the request then creates a View Model object and pass that object to the view.
View model object contains necessary data that needs to be displayed on the view.View reads data from the View Model object and renders the same to the response, that response is sent to MVC framework and then same is sent to the browser as a response. Browser renders the output.This is the execution flow of a request sent to MVC application.

Action Methods
By default, all methods defined in controller are treated as Action methods. An Action method executes when browser sends request.
Action method performs some operation according to business logic and after that returns the appropriate result back to the browser.
It is recommended to specify return type of Action method as ActionResult.

Example of Index action method:

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

Above Action method Index() will return a view named Index to the browser.

Below is the complete Home Controller code including Index() action method:

public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *