Roadmap › ASP.NET MVC 5 (.NET Framework) — Folder Structure, Request Life Cycle and Features › Module: Controllers and Views
Lessons in this course (10)
3. Controllers, actions and action results
Basic★ Must knowLesson 3 of 10
csharp
public class ProductsController : Controller
{
private readonly IProductService _products;
public ProductsController(IProductService products) => _products = products; // needs a DI container in MVC 5
public ActionResult Index(string q, int page = 1) => View(_products.Search(q, page));
public ActionResult Details(int id)
{
var p = _products.Get(id);
if (p == null) return HttpNotFound();
return View(p);
}
[HttpGet] public ActionResult Create() => View(new ProductEditModel());
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Create(ProductEditModel model)
{
if (!ModelState.IsValid) return View(model); // redisplay with validation messages
_products.Add(model);
TempData["Message"] = "Product created";
return RedirectToAction(nameof(Index)); // Post-Redirect-Get pattern
}
public async Task<ActionResult> Export() => File(await _products.ExportCsvAsync(), "text/csv", "products.csv");
public JsonResult Lookup(string term) => Json(_products.Lookup(term), JsonRequestBehavior.AllowGet);
}| ActionResult | Helper | Purpose |
|---|---|---|
ViewResult | View() | Render a view |
PartialViewResult | PartialView() | Render a partial (AJAX) |
RedirectToRouteResult | RedirectToAction() | Redirect to an action |
RedirectResult | Redirect(url) | Redirect to a URL |
JsonResult | Json() | JSON (GET needs AllowGet) |
ContentResult | Content() | Plain text/HTML |
FileResult | File() | Downloads |
HttpStatusCodeResult / HttpNotFoundResult | new HttpStatusCodeResult(400) / HttpNotFound() | Status codes |
EmptyResult | — | Nothing |
Action selectors: [HttpGet], [HttpPost], [ActionName("Delete")], [NonAction] (public method that isn't an action), [ChildActionOnly].