Part 11 and last part of the newbie guide. In this last article, we will talk about Web development as it is a vital skill in today's technological landscape, allowing you to create dynamic and easy to use applications, accessible from any browser. In this article, we will explore the fundamentals of developing web applications using ASP.NET Core, taking advantage of the features of the latest version of .NET 8 and C# 12.
1. What is ASP.NET Core?
ASP.NET Core is a modern, open-source, cross-platform framework for web application building. It supports a variety of development styles, including:
- Razor Pages: For page-focused scenarios.
- Model-View-Controller (MVC): Ideal for applications with complex UI logic.
- Minimal APIs: A lightweight approach to building APIs.
- Blazor: For building interactive web UIs with C# instead of JavaScript.
2. Creating a Simple Web Application
In this section, we’ll create a minimal web application using the latest ASP.NET Core features.
Step 1: Setting Up the Project
- Open a terminal or your preferred IDE (e.g., Visual Studio or VS Code).
- Run the following command to create a new ASP.NET Core project:
dotnet new web -n MyFirstWebApp
- Navigate to the project folder:
cd MyFirstWebApp
- Run the application:
dotnet run
Visit http://localhost:5000
in your browser to see your first ASP.NET Core application running.
Step 2: Adding an Endpoint with Minimal API
Minimal APIs are a streamlined way to define endpoints in ASP.NET Core. Open the Program.cs
file and add the following code:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Welcome to my first ASP.NET Core application!");
app.Run();
Rerun the application and visit the root URL to see the message displayed.
3. Understanding MVC (Model-View-Controller)
MVC is a design pattern that separates an application into three interconnected components:
- Model: Represents the application’s data and business logic.
- View: Handles the presentation layer (HTML, CSS, etc.).
- Controller: Handles user input and updates the model and view accordingly.
Let’s implement a simple MVC example:
Step 1: Adding MVC to the Project
- Update the
Program.cs
file to include MVC support:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Step 2: Creating a Controller
Create a folder named Controllers
in the project root and add a new file HomeController.cs
with the following code:
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
Step 3: Creating a View
- Create a folder named
Views
in the project root. - Inside
Views
, create another folder namedHome
. - Add a new file
Index.cshtml
in theHome
folder with the following content:
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome to ASP.NET Core MVC!</h1>
</body>
</html>
Rerun the application and visit the root URL to see your MVC-based page.
4. Building a Simple MVC Application: Student Management
Let’s extend our knowledge by creating a simple MVC application that manages a list of students.
Step 1: Define the Model
Add a new folder named Models
and create a file Student.cs
:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Step 2: Create the Controller
Add a new controller StudentController.cs
in the Controllers
folder:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
public class StudentController : Controller
{
private static List<Student> students = new List<Student>
{
new Student { Id = 1, Name = "Alice", Age = 20 },
new Student { Id = 2, Name = "Bob", Age = 22 }
};
public IActionResult Index()
{
return View(students);
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Student student)
{
if (ModelState.IsValid)
{
student.Id = students.Count + 1;
students.Add(student);
return RedirectToAction("Index");
}
return View(student);
}
}
Step 3: Create the Views
- In the
Views
folder, create a new folder namedStudent
. - Add a file
Index.cshtml
:
@model List<Student>
<!DOCTYPE html>
<html>
<head>
<title>Students</title>
</head>
<body>
<h1>Student List</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
@foreach (var student in Model)
{
<tr>
<td>@student.Id</td>
<td>@student.Name</td>
<td>@student.Age</td>
</tr>
}
</tbody>
</table>
<a href="/Student/Create">Add New Student</a>
</body>
</html>
- Add a file
Create.cshtml
:
@model Student
<!DOCTYPE html>
<html>
<head>
<title>Add Student</title>
</head>
<body>
<h1>Add New Student</h1>
<form asp-action="Create" method="post">
<label for="Name">Name:</label>
<input type="text" id="Name" name="Name" required />
<br />
<label for="Age">Age:</label>
<input type="number" id="Age" name="Age" required />
<br />
<button type="submit">Add Student</button>
</form>
</body>
</html>
Rerun the application and navigate to /Student
to manage students.
5. Best Practices
General Tips
- Use Dependency Injection to manage services and dependencies effectively.
- Validate user input at both client and server levels.
- Secure sensitive data with environment variables and the
UserSecrets
tool. - Use logging frameworks like Serilog for monitoring and debugging.
Keeping Code Clean
- Use DTOs (Data Transfer Objects) to separate data models from view models.
- Follow naming conventions and folder structures for maintainability.
Final Thoughts
With ASP.NET Core, you have a powerful framework at your disposal to create modern, scalable web applications. This final chapter of our guide introduces you to web development and provides a foundation to explore more advanced topics like API creation, authentication, and database integration. Happy coding and Happy New Year!
Top comments (0)