ASP.NET 8 MVC Tutorial for Beginners - C# web development made easy

4 min read 1 year ago
Published on Aug 03, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial will guide you through building a web application using ASP.NET MVC with C#. You will learn how to create an expense tracking application called "Spend Smart" from scratch. This application will allow users to add, edit, delete, and view their expenses, utilizing an in-memory database with Entity Framework.

Chapter 1: Setting Up the ASP.NET MVC Project

  1. Open Visual Studio 2022

    • Create a new project by selecting ASP.NET Core Web App (Model-View-Controller) as the template.
    • Name the project "Spend Smart" and ensure you select .NET 8 without any authentication or Docker options enabled.
  2. Run the Application

    • Start the application by clicking the debug button or pressing Ctrl + F5.
    • Confirm that the application is running and accessible via Localhost at a specified port.
  3. Understand the Project Structure

    • Familiarize yourself with the folders: Controllers, Models, and Views.
    • The default controller is HomeController, which contains an Index method rendering the homepage.

Chapter 2: Creating the Expense Model

  1. Add a New Model

    • Right-click the Models folder and select Add > Class.
    • Name the class Expense and define properties:
      public class Expense
      {
          public int ID { get; set; }
          public decimal Value { get; set; }
          public string? Description { get; set; }
      }
      
  2. Create a View for Displaying Expenses

    • Right-click the Views folder, choose Add > View, and name it Expenses.
    • Set up the view to display a list of expenses.
  3. Implement Routing Logic

    • In Program.cs, configure the routing to include the new expenses view:
      app.MapControllerRoute(
          name: "default",
          pattern: "{controller=Home}/{action=Index}/{id?}");
      

Chapter 3: Adding Functionality to Create New Expenses

  1. Create a Form for New Expenses

    • Right-click on the HomeController, add a new action called CreateEditExpense.
    • Create a view for this action with a form allowing users to input ID, Value, and Description.
  2. Submit the Form

    • Update the form to submit to the CreateEditExpense action:
      <form asp-action="CreateEditExpense" method="post">
          <!-- Form fields for ID, Value, Description -->
          <button type="submit" class="btn btn-primary">Submit</button>
      </form>
      
  3. Handle the Form Submission in the Controller

    • Add logic to CreateEditExpense to save the expense to the database. Use Entity Framework to add the expense to the in-memory database.

Chapter 4: Connecting to an In-Memory Database

  1. Install Entity Framework Packages

    • Use NuGet Package Manager to install:
      • Microsoft.EntityFrameworkCore.InMemory
      • Microsoft.EntityFrameworkCore
  2. Set Up Database Context

    • Create SpendSmartDbContext derived from DbContext and include a DbSet<Expense> property.
  3. Configure the Database Context in Program.cs

    • Add the context to the service container:
      builder.Services.AddDbContext<SpendSmartDbContext>(options =>
          options.UseInMemoryDatabase("SpendSmartDB"));
      

Chapter 5: Displaying and Managing Expenses

  1. Display Expenses in the View

    • Modify the expenses view to show a table of all expenses, including columns for ID, Value, Description, and Actions (Edit/Delete).
  2. Implement Editing and Deleting Expenses

    • Add actions in HomeController to handle editing and deleting expenses.
    • Update the expenses view to include links/buttons for editing and deleting:
      <a asp-action="CreateEditExpense" asp-route-id="@expense.ID">Edit</a>
      <a asp-action="DeleteExpense" asp-route-id="@expense.ID">Delete</a>
      
  3. Handle Deletion Logic

    • In the DeleteExpense action, find the expense by ID and remove it from the database, then redirect to the expenses view.
  4. Add Total Expenses Calculation

    • In the expenses view, calculate the total of all expenses and display it at the top of the list using a ViewBag:
      ViewBag.TotalExpenses = context.Expenses.Sum(e => e.Value);
      

Conclusion

You've successfully built a comprehensive expense tracking application using ASP.NET MVC and C#. You learned how to set up a project, create models, implement CRUD operations, and display data in a user-friendly interface. As a next step, consider exploring further features like user authentication, data persistence with SQL databases, or enhancing the UI with more advanced front-end frameworks.