DEV Community

Janki Mehta
Janki Mehta

Posted on

ASP.NET and MVC Tutorial Guide

Introduction to ASP.NET MVC

ASP.NET MVC is a powerful web development framework from Microsoft that provides a model-view-controller architecture for building dynamic and robust web applications. In this comprehensive tutorial, we will learn the fundamentals of ASP.NET MVC from the ground up.

Overview of MVC Architecture

The Model-View-Controller (MVC) is a software architectural pattern that separates an application into three interconnected components - the Model, the View, and the Controller. Here is a brief overview of each component:

  • Model: Represents the business logic and data in the application. It manages the data and business rules of the application.
  • View: Renders the UI of the application. It displays data from the model to the user.
  • Controller: Handles user interaction and controls communication between model and view. It receives input from users and invokes appropriate models and views. The main advantage of MVC architecture is the separation of concerns between the presentation layer (view), business logic (model), and input handling (controller). This promotes parallel development and allows easier maintenance by decoupling components.

Getting Started

Let's now setup a simple ASP.NET MVC application from scratch to understand the basic components.

Prerequisites

  • Visual Studio 2019 or higher
  • .NET Framework 4.7.2 or higher

Create New ASP.NET MVC Project

  • Open Visual Studio and click on Create a new project.
  • Select ASP.NET Web Application (.NET Framework) template.
  • Name the project MyMVCApp and click Create.
  • Select MVC template and click Create.

This will create a new ASP.NET MVC project with default files and folders.

Project Structure

The generated project has the following structure:

  • Models: Contains model classes representing data in the application.
  • Views: Holds UI template files mapped to controller actions.
  • Controllers: Handles user requests and application flow. Each controller class is mapped to a route.
  • Content: Contains static assets like CSS, images, and JavaScript files.
  • Scripts: Houses JavaScript files.
  • Global.asax: Application startup and configuration file.

Run the Application

  • Press Ctrl + F5 to run the application without debugging. This will launch the default homepage.
  • Let's now understand these generated files and folders in more detail.

Models

  • The Models folder contains classes that represent business data or entities required by the application. For example, a blogging application may have model classes like Post, Category, and Comment.
  • Models encapsulate data and business logic related to that data. They are usually connected to a database and are responsible for managing data using business rules.

Create Model Class

Let's add a Product model representing products in an ecommerce application.
Product.cs

namespace MyMVCApp.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Category { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode

This model contains Id, Name, Price, and Category properties representing product data.
You can include data validation attributes on model properties to enforce business rules. Models can also contain methods to implement business logic for that model.

Controllers

Controllers handle and respond to user requests. They receive input, invoke appropriate model and view, and return a response.

  • In ASP.NET MVC, controllers are responsible for:
  • Handling HTTP requests and generating HTTP responses.
  • Working with models to execute application logic and persist data.
  • Selecting views to render output. Controllers provide the 'C' in the MVC pattern. Let's go through some key characteristics of MVC controllers:

Routing

  • Each public controller class is mapped to a route in the format /ControllerName/ActionName. For example, HomeController maps to /Home/Index.
  • Routing is defined in RouteConfig.cs file under App_Start folder.

Actions

  • Controller methods are called actions. Actions handle user input and invoke model & view.
  • Action methods must be public and usually return an ActionResult.
  • Common action method returns types:
  • ViewResult - Renders a view template.
  • PartialViewResult - Renders a partial view.
  • ContentResult - Returns a text response.
  • JsonResult - Returns a JSON response.
  • FileResult - Returns a binary file.
  • RedirectResult - Redirects to a new URL.

Filters

  • Filters allow running logic before/after action execution e.g. authentication, caching etc.
  • Some common filters provided by MVC:
  • Authorization: Enables authorization on actions.
  • ActionFilter: Code runs before/after all actions.
  • ExceptionFilter: Handles exceptions from controller actions.

Let's create a simple controller.

Create Product Controller

Add a new ProductController class under Controllers folder.
ProductController.cs

public class ProductController : Controller
{
   //GET action method
   public ActionResult List()  
   {
      return View();
   }    
   //GET action method
   public ActionResult Details(int id)
   {
      return View();
   }
   //POST action method
   [HttpPost]
   public ActionResult Create(Product model)
   {
      //Save product
      return RedirectToAction("List");  
   }
}
Enter fullscreen mode Exit fullscreen mode
  • The List action renders List view to display products.
  • Details action renders product details.
  • Create action saves new product and redirects back to List view.

Views

  • Views represent the user interface of the application. They render HTML output displayed in the browser.
  • Views mainly contain UI markup like HTML, CSS and static resources to build page layout. They also display data passed from controllers.

View Engine

  • ASP.NET MVC supports different view engines like Razor, Web Forms etc.
  • Razor is the default view engine. Razor views have .cshtml extension.
  • Razor provides a cleaner HTML markup with C# code for dynamic content.

Layouts

  • Layouts allow you to build reusable page templates.
  • Layouts define common UI sections like header, footer etc.
  • Child views add content in the RenderBody() section.
  • Layouts are stored in /Views/Shared folder by convention.

Partial Views

  • Partial views represent reusable UI components invoked from views.
  • They are stored as .cshtml files within a /Views/Shared/EditorTemplates folder.
  • Partials are rendered using @Html.Partial("Name").

Let's create a simple view.

Create List View
Add a new List.cshtml view for the List action we defined earlier.
List.cshtml

@model IEnumerable<Product>

<h1>Product List</h1>
<table>
   <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Price</th>
   </tr>   
   @foreach(var product in Model)
   {
      <tr>
         <td>@product.Id</td>  
         <td>@product.Name</td>
         <td>@product.Price</td>  
      </tr>
   }
</table>
Enter fullscreen mode Exit fullscreen mode
  • @model directive specifies the model type.
  • We loop through the model data to generate a product list table.

Run the application now and browse to /Product/List to view the product list page rendered.

MVC Request Life Cycle

When a request comes in, ASP.NET MVC executes a standard life cycle to process the request and return a response:

  • Routing: Determines the matching controller and action.
  • Model Binding: Binds request data to action method parameters.
  • Filters: Filter logic executes before/after actions.
  • Action Invocation: Matched action method is invoked.
  • View Rendering: Selected view template is rendered.
  • Filters: Response filters like output caching run after view rendering.
  • Response: HTTP response is returned. Understanding this pipeline helps debug issues and write custom components like filters.

Advance

We've covered the major components of ASP.NET MVC. Here are some more advanced topics you may encounter:

  • Authentication/Authorization: Securing your application from unauthorized access.
  • Validation: Validating model data both on client-side and server-side.
  • AJAX: Updating portions of page without full postback using ajax and jQuery.
  • Dependency Injection: Injecting dependencies into controllers for loose coupling.
  • Unit Testing: Writing automated tests for controllers and models.
  • **Web APIs: **Building RESTful web APIs for mobile and web clients.
  • Identity: Managing user accounts, profiles, and roles.
  • Entity Framework: Using ORM framework to work with database.
  • Caching: Caching data for better performance.
  • Bundling and Minification: Bundling and minifying CSS/JavaScript files.
  • **Async Controllers: **Using async/await for improved scalability.
  • WebSockets: Enabling real-time communication between server and client.
  • Deployment: Deploying application to IIS or cloud platforms.

Summary

ASP.NET MVC is a robust web development framework from Microsoft that implements the model-view-controller (MVC) architectural pattern. In this comprehensive tutorial, we learned how to create an ASP.NET MVC application from scratch. We discussed key concepts like models for encapsulating business logic, controllers for handling requests, and views for rendering UI. We created a simple model, controller, and view to display a list of products. We also covered the MVC request lifecycle and advanced features like authentication, validation, AJAX, etc. The separation of concerns promoted by MVC results in maintainable and testable code. ASP.NET MVC is an excellent choice for building dynamic web applications using the MVC pattern.

Top comments (0)