ASP.NET Core  

ASP.NET MVC Cheatsheet – A Beginner-Friendly Guide

Introduction

ASP.NET MVC is a framework used to build web applications using the Model-View-Controller pattern. It helps in separating the application logic, user interface, and data, which makes the code easy to manage, test, and scale. This guide is a simple reference for key topics in ASP.NET MVC, including definitions, short examples, and tips. It is useful for both beginners and those who need a quick refresh.

1. Model-View-Controller (MVC) Pattern

  • Definition: MVC is a design pattern that separates an application into three parts:

    • Model: Handles data and business logic.
    • View: Displays the data to the user.
    • Controller: Handles user input and updates the Model or View.
  • Example
    public class Student {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
  • Important: This pattern improves the testability and maintainability of your code.

2. Routing

  • Definition: Routing maps URLs to controller actions.
  • Example
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    
  • Important: Defined in RouteConfig.cs, used by Global.asax.

3. Controller

  • Definition: A controller handles incoming HTTP requests and returns a response.
  • Example
    public class HomeController : Controller {
        public ActionResult Index() {
            return View();
        }
    }
    
  • Important: Action methods return ActionResult.

4. ActionResult Types

  • Definition: ActionResult can return different types of responses.
  • Example
    return View();            // Returns HTML view
    return RedirectToAction("About");
    return Json(data, JsonRequestBehavior.AllowGet);
    
  • Important: Choose based on the type of response needed.

5. Views

  • Definition: Views are UI templates written using Razor syntax.
  • Example (Index.cshtml)
    <h2>Hello @Model.Name</h2>
    
  • Important: Views are strongly typed using @model directive.

6. Strongly Typed Views

  • Definition: Views that are linked to a specific model type.
  • Example
    @model YourApp.Models.Student
    <p>Name: @Model.Name</p>
    
  • Important: Helps avoid errors at runtime by providing IntelliSense.

7. HTML Helpers

  • Definition: Methods to create HTML elements in views.
  • Example
    @Html.TextBoxFor(model => model.Name)
    
  • Important: Useful for creating forms and binding values to models.

8. Form Submission

  • Definition: Form data is posted to a controller using HttpPost.
  • Example
    [HttpPost]
    public ActionResult Create(Student student) {
        // Save to DB
        return RedirectToAction("Index");
    }
    
  • Important: Use [HttpPost] to handle form submissions.

9. Model Binding

  • Definition: Automatically maps form values to model properties.
  • Example
    public ActionResult Edit(Student student) {
        // 'student' is populated from form data
    }
    
  • Important: Names of form fields must match model property names.

10. Model Validation

  • Definition: Data annotations are used to validate user input.
  • Example
    [Required]
    [StringLength(50)]
    public string Name { get; set; }
    
  • Important: Validations are enforced on both the client and server sides.

11. TempData, ViewBag, ViewData

  • TempData: Used to pass data between actions (persists for one request).
  • ViewBag: A Dynamic object, used to pass data from the controller to the view.
  • ViewData: Dictionary object, similar to ViewBag.
  • Example
    ViewBag.Message = "Hello";
    return View();
    
  • Important: Prefer ViewModel for passing complex data.

12. Filters

  • Definition: Used for cross-cutting concerns like logging, authorization, etc.
  • Example
    [Authorize]
    public ActionResult Secret() {
        return View();
    }
    
  • Important: Built-in filters include Authorize, HandleError, etc.

13. Partial Views

  • Definition: A part of a view reused in multiple pages.
  • Example
    @Html.Partial("_StudentDetails", student)
    
  • Important: Good for reusable UI components.

14. Layout View

  • Definition: Acts like a master page for consistent layout.
  • Example (_Layout.cshtml)
    <body>
      <div>@RenderBody()</div>
    </body>
    
  • Important: Set the layout in views using @{ Layout = "_Layout.cshtml"; }.

15. Bundling and Minification

  • Definition: Combines and compresses CSS and JS files.
  • Example
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));
    
  • Important: Improves load time by reducing request size.

16. Error Handling

  • Definition: Catch and handle errors gracefully.
  • Example
    [HandleError]
    public class HomeController : Controller {
        public ActionResult Error() {
            throw new Exception("Test");
        }
    }
    
  • Important: Use custom error pages via web.config.

17. Scaffolding

  • Definition: Automatically generates a controller and views for a model.
  • Example: Right-click Model → Add → Controller → Use Scaffolding.
  • Important: Saves time during prototyping.

18. Entity Framework Integration

  • Definition: Used for database operations.
  • Example
    public class SchoolContext : DbContext {
        public DbSet<Student> Students { get; set; }
    }
    
  • Important: Supports Code First and Database First approaches.

19. Dependency Injection (DI)

  • Definition: Inject dependencies instead of creating them inside the class.
  • Example
    public HomeController(IStudentService service) {
        _service = service;
    }
    
  • Important: Use built-in or external DI containers like Unity or Autofac.

20. Security

  • Authentication: Use Identity for user login and registration.
  • Authorization: Use [Authorize] to restrict access.
  • Anti-Forgery
    @Html.AntiForgeryToken()
    
  • Important: Always validate and sanitize inputs.\

21. Areas

  • Definition: Areas are used to split a large application into smaller sections or modules.
  • Example
    // In AreaRegistration
    public class AdminAreaRegistration : AreaRegistration {
        public override string AreaName => "Admin";
    
        public override void RegisterArea(AreaRegistrationContext context) {
            context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
    
  • Important: Helps organize projects with many controllers and views.

22. Custom Route Constraints

  • Definition: Custom logic used to restrict which URLs match a route.
  • Example
    routes.MapRoute(
        name: "YearRoute",
        url: "{controller}/{action}/{year}",
        constraints: new { year = @"\d{4}" }
    );
    
  • Important: Use regular expressions or custom classes to define constraints.

23. Custom HTML Helpers

  • Definition: Create your own helper methods for reusable HTML elements.
  • Example
    public static class HtmlExtensions {
        public static MvcHtmlString HelloText(this HtmlHelper helper, string name) {
            return new MvcHtmlString($"<p>Hello {name}</p>");
        }
    }
    
  • Important: Add namespace to web.config under <pages><namespaces>.

24. JsonResult

  • Definition: Used to return JSON data from a controller.
  • Example
    public JsonResult GetStudent() {
        var student = new { Id = 1, Name = "Riya" };
        return Json(student, JsonRequestBehavior.AllowGet);
    }
    
  • Important: Useful for AJAX requests.

25. File Upload

  • Definition: Upload files to server using a form.
  • Example
    <form enctype="multipart/form-data" method="post">
        <input type="file" name="file" />
        <input type="submit" />
    </form>
    
    [HttpPost]
    public ActionResult Upload(HttpPostedFileBase file) {
        if (file != null) {
            var path = Path.Combine(Server.MapPath("~/Uploads"), file.FileName);
            file.SaveAs(path);
        }
        return View();
    }
    
  • Important: Set enctype="multipart/form-data" in the form.

26. Session Management

  • Definition: Store user data between requests.
  • Example
    Session["UserName"] = "Riya";
    var name = Session["UserName"];
    
  • Important: Avoid overusing sessions due to memory concerns on the server.

27. Using ViewModels

  • Definition: A class used to combine multiple models or additional data for the view.
  • Example
    public class StudentViewModel {
        public Student Student { get; set; }
        public List<Subject> Subjects { get; set; }
    }
    
  • Important: Keeps views clean and focused.

28. AJAX with jQuery

  • Definition: Load data or perform actions without refreshing the page.
  • Example
    $.get("/Student/GetDetails", function(data) {
        $("#studentDiv").html(data);
    });
    
  • Important: Controller action can return PartialView or JsonResult.

29. Web.config Settings

  • Definition: Configuration file for ASP.NET applications.
  • Example
    <connectionStrings>
        <add name="DefaultConnection" connectionString="..." providerName="System.Data.SqlClient" />
    </connectionStrings>
    
  • Important: Used for settings like connection strings, custom errors, etc.

30. Anti-Forgery Token

  • Definition: Prevents Cross-Site Request Forgery (CSRF) attacks.
  • Example
    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
    }
    
    [ValidateAntiForgeryToken]
    public ActionResult Save(Student student) {
        // Save logic
    }
    
  • Important: Always include in forms that modify data.

31. Authorization and Authentication

  • Definition: Control access to controllers and actions.
  • Example
    [Authorize]
    public ActionResult Dashboard() {
        return View();
    }
    
  • Important: Use [AllowAnonymous] to allow public access if needed.

32. Custom Error Pages

  • Definition: Show user-friendly messages instead of raw errors.
  • Example in web.config
    <customErrors mode="On">
        <error statusCode="404" redirect="~/Error/NotFound" />
    </customErrors>
    
  • Important: Always test error behavior after deployment.

33. Output Caching

  • Definition: Caches the result of controller actions to improve performance.
  • Example
    [OutputCache(Duration = 60)]
    public ActionResult News() {
        return View();
    }
    
  • Important: Avoid caching dynamic or user-specific content.

34. Action Filters

  • Definition: Execute logic before or after action methods.
  • Example
    public class LogActionFilter : ActionFilterAttribute {
        public override void OnActionExecuting(ActionExecutingContext filterContext) {
            // Log here
        }
    }
    
  • Important: Can be used for logging, exception handling, etc.

Conclusion

ASP.NET MVC is a strong and flexible framework for building web applications. Knowing the key concepts like routing, controllers, views, model binding, and validation helps in creating clean and maintainable applications. This cheatsheet gives a quick look at the important topics, with examples and points to remember. It is a useful reference when you are coding or revising.