In Asp.Net MVC, Controllers are main components which responsible for every user action. For example user clicks on some button controller decides which method it has to call based on button. Basically controllers are the classes which contains methods and these methods called by Asp.Net MVC routing framework.
Let's discuss Controller in Asp.Net MVC by creating simple example. Open Microsoft Visual Studio 2013 => create simple Asp.Net MVC application as explained in my previous article at https://www.techinfocorner.com/post/Create-Simple-ASPNET-MVC-Application. As explained in that article ee added the HomeController.cs controller as shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SimpleMVCApplication.Controllers
{
public class HoomeController : Controller
{
//
// GET: /Hoome/
public ActionResult Home()
{
return View();
}
public ActionResult Company()
{
return View();
}
public ActionResult Employee()
{
return View();
}
}
}
As shown above Home Controller has Home, Company, and Employee action methods. If user enters http://localhost/SimpleMVCApplication/Home in browser, Home action method responds to the request. If user enters http://localhost/SimpleMVCApplication/Home/Company in browser, Company action method in Home controller responds. That means based on URL structure Asp.Net MVC engine passes the request. In the UK field, after base uri first field is the controller name followed by the action method.
The
main job of Controller is to tell Asp.Net MVC what to do next by returning
Action result, not how to do.For example Controller returns ViewResult means
asking Asp.Net MVC to render some View.
There are different ActionResults which can be returned by Controller, we
discuss about those below.
Content() – returns ContentResult that renders only text
File() – returns FileResult that renders contents of a file
JavaScript() – returns JavaScriptResult that renders java script
Json() - Returns a JsonResult that serializes an object and renders it in JavaScript Object Notation (JSON) format
PartialView() – returns PartialViewResult which renders only contents of the view
Redirect() – returns a RedirectResult that renders a 302 (temporary) status code to redirect the user to a given URL, e.g., “302 /Home/Company”.
RedirectToAction() and RedirectToRoute() – These are also like the Redirect(), only the framework dynamically determines the external URL by querying the routing engine.
View() - Returns a ViewResult that renders a view.
HttpNotFound() - returns an HttpNotFoundResult that renders a 404 HTTP status code response.