ASP.NET Core MVC Cheat Sheet

Introduction to ASP.NET Core MVC

ASP.NET Core MVC is a powerful framework for building web applications using the Model-View-Controller design pattern. This cheat sheet provides a quick reference for common concepts and syntax.

Controllers

Controllers handle incoming requests, interact with models, and select views to render.

Creating a Controller

public class HomeController : Controller { public IActionResult Index() { return View(); // Renders Views/Home/Index.cshtml } public IActionResult About() { ViewBag.Message = "Your application description page."; return View(); // Renders Views/Home/About.cshtml } public IActionResult Contact(string name) { ViewData["Greeting"] = $"Hello, {name ?? "Guest"}!"; return View(); // Renders Views/Home/Contact.cshtml } public IActionResult Data() { var data = new { Id = 1, Name = "Sample Item" }; return Json(data); // Returns JSON } public IActionResult RedirectToGoogle() { return Redirect("https://www.google.com"); } }

Controller Actions & Return Types

Return Type Description Example
IActionResult Base interface for action results. public IActionResult Index()
ViewResult Renders a view. return View("MyView", model);
PartialViewResult Renders a partial view. return PartialView("_MyPartial", model);
RedirectResult Performs an HTTP redirect. return Redirect("/products");
RedirectToActionResult Redirects to another action. return RedirectToAction("Index", "Home");
NotFoundResult Returns a 404 Not Found status. return NotFound();
OkResult Returns a 200 OK status. return Ok();
StatusCodeResult Returns a specified HTTP status code. return StatusCode(401);
JsonResult Returns JSON data. return Json(new { msg = "Success" });

Views

Views display data to the user and contain Razor syntax for dynamic content.

Razor Syntax Basics

Layouts and Partials

Tag Helpers

Tag helpers enable server-side C# code to participate in HTML element parsing and rendering.

<!-- Forms --> <form asp-controller="Products" asp-action="Create" method="post"> <input asp-for="ProductName" /> <button type="submit">Save</button> </form> <!-- Anchor Tag Helper --> <a asp-controller="Home" asp-action="About">About Us</a> <!-- Image Tag Helper --> <img src="~/images/logo.png" alt="Logo" /> <!-- Label Tag Helper --> <label asp-for="Email"></label> <input asp-for="Email" class="form-control" />

Models

Models represent the data and business logic of the application.

Example Model

using System.ComponentModel.DataAnnotations; public class Product { public int Id { get; set; } [Required] [StringLength(100)] public string Name { get; set; } [Range(0.01, 1000.00)] public decimal Price { get; set; } public string Description { get; set; } }

Data Annotations for Validation

Used to enforce data integrity.

Routing

Defines how URLs are mapped to controller actions.

Convention-Based Routing (Startup.cs)

app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");

Attribute Routing

Applied directly to controllers and actions.

[Route("api/[controller]")] public class ProductsApiController : ControllerBase { [HttpGet] // Maps to GET /api/Products public IActionResult GetAll() { ... } [HttpGet("{id}")] // Maps to GET /api/Products/{id} public IActionResult GetById(int id) { ... } [HttpPost] // Maps to POST /api/Products public IActionResult Create([FromBody] Product product) { ... } }
[Route("products")] public class ProductsController : Controller { [Route("list")] // Maps to /products/list public IActionResult List() { ... } [Route("details/{productId:int}")] // Maps to /products/details/{productId} public IActionResult Details(int productId) { ... } }

View Components

Reusable UI components that can be called from views or controllers.

Creating a View Component

// MyViewComponent.cs using Microsoft.AspNetCore.Mvc; public class MyViewComponent : ViewComponent { public IViewComponentResult InvokeAsync(string title) { ViewBag.ComponentTitle = title; return View(); // Renders Views/Shared/Components/MyViewComponent/Default.cshtml } }

Invoking a View Component in a View

@await Component.InvokeAsync("MyViewComponent", new { title = "Welcome!" })

Tag Helpers

Tag Helpers allow you to write HTML with C# logic, providing a more familiar syntax for front-end developers.

Common Tag Helpers

Tag Helper Purpose Example
<form asp-controller="..." asp-action="..."> Renders an HTML form with action and controller attributes. <form asp-controller="User" asp-action="Login">
<a asp-controller="..." asp-action="..."> Renders an anchor tag with URL routing. <a asp-controller="Product" asp-action="Details" asp-route-id="123">View Product</a>
<input asp-for="..."> Generates an input element for a model property, including validation attributes. <input asp-for="Email" class="form-control" />
<label asp-for="..."> Generates a label for a model property. <label asp-for="Password"></label>
<div asp-validation-for="..."> Renders a validation message for a model property. <div asp-validation-for="Name" class="text-danger"></div>
<environment include="..." exclude="..."> Conditionally renders content based on the environment (Development, Staging, Production). <environment include="Development">...</environment>

Filters

Filters allow you to inject pre- and post-processing logic into the MVC execution pipeline.

Types of Filters

Applying Filters

Globally (in Startup.cs)

services.AddControllersWithViews(options => { options.Filters.Add(new AuthorizeFilter()); // Applies AuthorizeFilter to all actions });

By Controller

[Authorize] // Applies AuthorizeFilter to all actions in this controller public class AdminController : Controller { // ... actions }

By Action Method

public class HomeController : Controller { [AllowAnonymous] // Allows anonymous access to this specific action public IActionResult PublicAction() { ... } [HttpPost] [ValidateAntiForgeryToken] // Protects against CSRF attacks public IActionResult SecureAction() { ... } }