BIT351 ยท 2081 ยท 10 marks
How do you create Controllers, Actions and Action results? Explain.
How do you create Controllers, Actions and Action results? Explain.[10]
Quick answer
A Controller is a class that handles incoming HTTP requests, processes user input, interacts with the model, and returns an appropriate response (view or data).
Controllers, Actions, and Action Results in ASP.NET MVC
Note: The reference notes did not contain specific content on this topic. The following answer is based on standard ASP.NET MVC curriculum as taught in TU BSc CSIT, using correct and widely accepted terminology.
1. Controllers in ASP.NET MVC
Rules for Creating a Controller:
- The class name must end with "Controller" (e.g.,
HomeController) - It must inherit from the
Controllerbase class - It is placed inside the
Controllersfolder of the MVC project - It must be a public class
Syntax to Create a Controller:
using System.Web.Mvc;
namespace MyApp.Controllers
{
public class HomeController : Controller
{
// Actions go here
}
}
Ways to Create a Controller:
- Manually - Create a class file in the Controllers folder following the naming convention.
- Using Scaffolding - Right-click on Controllers folder > Add > Controller > Select template (Empty, with Read/Write actions, etc.)
2. Actions in ASP.NET MVC
An Action is a public method inside a controller that responds to a specific HTTP request (GET, POST, etc.).
Rules for Action Methods:
- Must be a public method
- Must not be static
- Must not have
[NonAction]attribute (unless intentionally excluded) - Returns an ActionResult or its derived types
Example of Action Methods:
public class StudentController : Controller
{
// Action for GET request
public ActionResult Index()
{
return View();
}
// Action for displaying details
public ActionResult Details(int id)
{
// fetch student by id
return View();
}
// Action for GET - show form
[HttpGet]
public ActionResult Create()
{
return View();
}
// Action for POST - submit form
[HttpPost]
public ActionResult Create(Student student)
{
if (ModelState.IsValid)
{
// save to database
return RedirectToAction("Index");
}
return View(student);
}
}
Action Selectors (Attributes):
| Attribute | Description |
|---|---|
[HttpGet] | Handles GET requests |
[HttpPost] | Handles POST requests |
[HttpPut] | Handles PUT requests |
[HttpDelete] | Handles DELETE requests |
[ActionName("name")] | Assigns a different name to the action |
[NonAction] | Excludes a public method from being an action |
3. Action Results in ASP.NET MVC
An ActionResult is the return type of an action method. It is an abstract base class from which all specific result types are derived. It represents the result of executing an action method.
Common ActionResult Types:
| ActionResult Type | Helper Method | Description |
|---|---|---|
ViewResult | View() | Renders a view (HTML page) |
PartialViewResult | PartialView() | Renders a partial view |
RedirectResult | Redirect() | Redirects to a URL |
RedirectToRouteResult | RedirectToAction() | Redirects to another action |
ContentResult | Content() | Returns plain text/string content |
JsonResult | Json() | Returns JSON formatted data |
FileResult | File() | Returns a file to download |
EmptyResult | (none) | Returns nothing (void equivalent) |
HttpNotFoundResult | HttpNotFound() | Returns 404 error |
Examples of Different Action Results:
public class DemoController : Controller
{
// Returns a View
public ActionResult Index()
{
return View();
}
// Returns JSON data
public JsonResult GetData()
{
var data = new { Name = "Ram", Age = 20 };
return Json(data, JsonRequestBehavior.AllowGet);
}
// Returns plain content
public ContentResult ShowMessage()
{
return Content("Hello from ASP.NET MVC!");
}
// Redirects to another action
public ActionResult GoHome()
{
return RedirectToAction("Index", "Home");
}
// Returns a file
public FileResult DownloadFile()
{
byte[] fileBytes = System.IO.File.ReadAllBytes(
Server.MapPath("~/Files/sample.pdf"));
return File(fileBytes, "application/pdf", "sample.pdf");
}
// Returns 404
public ActionResult FindStudent(int id)
{
if (id <= 0)
return HttpNotFound();
return View();
}
}
4. Summary Diagram
HTTP Request
|
v
Controller (inherits Controller class)
|
v
Action Method (public method, returns ActionResult)
|
v
ActionResult (ViewResult / JsonResult / RedirectResult ...)
|
v
HTTP Response (HTML / JSON / File / Redirect ...)
5. Key Points to Remember
- A Controller handles requests and inherits from
Controller. - An Action is a public method inside a controller that processes a request.
- An ActionResult is the return type that determines what response is sent back to the client.
- The
View()method returns aViewResultwhich renders an HTML page. RedirectToAction()is used to redirect from one action to another.Json()is used in AJAX-based applications to return JSON data.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.