Controllers
The controller is responsible for the request made by the browser, each request is mapped to a particular controller.
The controller can return a view or redirect to another controller.
The controller is just a class derived from the base System.Web.Mvc.Controller class.
Controller Actions
Action is a method on a controller which gets called when you enter a URL in the browser address.
A controller action needs to be a public method of a controller class.
Controller action methods cannot be overloaded.
Action Results
A controller returns an action result in response to the browser request.
ViewResult – Represents HTML and markup.
EmptyResult – Represents no result.
RedirectResult – Represents a redirection to a new URL.
JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application.
JavaScriptResult – Represents a JavaScript script.
ContentResult – Represents a text result.
FileContentResult – Represents a downloadable file (with the binary content).
FilePathResult – Represents a downloadable file (with a path).
FileStreamResult – Represents a downloadable file (with a file stream).
An action result is not passed directly instead the following is passed:
View – Returns a ViewResult action result.
namespace MvcApplication1.Controllers { public class BookController : Controller { public ActionResult Index() { // Add action logic here return View(); } } }
Redirect – Returns a RedirectResult action result.
RedirectToAction – Returns a RedirectToRouteResult action result.
using System.Web.Mvc; namespace MvcApplication1.Controllers { public class CustomerController : Controller { public ActionResult Details(int? id) { if (!id.HasValue) return RedirectToAction("Index"); return View(); } } }
RedirectToRoute – Returns a RedirectToRouteResult action result.
Json – Returns a JsonResult action result.
JavaScriptResult – Returns a JavaScriptResult.
Content – Returns a ContentResult action result.
using System.Web.Mvc; namespace MvcApplication1.Controllers { public class StatusController : Controller { public ActionResult Index() { return Content("Hello World!"); } } }
File – Returns a FileContentResult, FilePathResult, or FileStreamResult depending on the parameters passed to the method.
HttpUnauthorizedResult – forces the user to login.
Live as if you were to die tomorrow. Learn as if you were to live forever.. -Mahatma Gandhi