Creating a Form with Validations in ASP.NET Core MVC
Written on
Chapter 1: Introduction to Form Validation
In our previous discussion, we explored foundational concepts. Now, let's dive deeper into a crucial aspect: form validation. It's essential to ensure that users provide valid input; without proper validation, our application may encounter errors.
We will be using .NET version 8.0.204 for this tutorial.
Creating a New Project
To get started, navigate to your project directory and execute the following commands in your terminal. Use the cd command to enter the FormValidation folder:
dotnet new globaljson --sdk-version 8.0.204 --output FormValidation
dotnet new mvc --no-https --output FormValidation --framework net8.0
dotnet new sln -o FormValidation
dotnet sln FormValidation add FormValidationModel
Next, we will create a file called Todo.cs within the Models folder. This file will outline the structure of a "todo" object, which includes a label and a status.
namespace FormValidation.Models;
public class Todo
{
public string? Label { get; set; }
public string? Status { get; set; }
}
Creating Todo Logic
Since we currently don't have any todos, let's add a form to facilitate the creation of new todos. Modify the HomeController to introduce a new method that will return the HTML form.
using Microsoft.AspNetCore.Mvc;
namespace FormValidation.Controllers;
public class HomeController : Controller
{
public IActionResult Index()
{
return View();}
public ViewResult TodoForm() // new
{
return View();}
}
Now, let's create an HTML skeleton in the Views/Home directory and name this file TodoForm.cshtml.
@{
Layout = null;
}
<html>
<head>
<title>Todo Form</title>
</head>
<body>
<h1>Todo Form</h1>
</body>
</html>
To access the form, we need to add a link in Views/Home/Index.cshtml.
@{
Layout = null;
}
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>Todo List</h1>
<p>Todos go here</p>
<a asp-action="TodoForm">Add Todo</a>
</body>
</html>
Here, the asp-action attribute serves as a tag helper, directing the framework to generate a URL pointing to the specified action method.
Now, run the application using dotnet run. You should see a link on the index page, and clicking the "Add Todo" link should lead you to the todo form page.
Implementing Form Functionality
At this point, the current form in TodoForm.cshtml is non-functional. To rectify this, we must take two additional steps: define the form and establish the form submission process.
@model Todo
@{
Layout = null;
}
<html>
<head>
<title>Todo Form</title>
</head>
<body>
<h1>Todo Form</h1>
<form method="post">
<label>Label:</label>
<input type="text" asp-for="Label" />
<label>Status:</label>
<input type="text" asp-for="Status" />
<button type="submit">Create</button>
</form>
</body>
</html>
We will manage GET and POST requests through distinct methods, keeping the controller code organized since the two methods serve different purposes. The GET method renders the page with a form, while the POST method processes the form submission. Notably, we will redirect back to the index page after submission.
using FormValidation.Models;
using Microsoft.AspNetCore.Mvc;
namespace FormValidation.Controllers;
public class HomeController : Controller
{
public IActionResult Index()
{
return View();}
[HttpGet]
public ViewResult TodoForm()
{
return View();}
[HttpPost]
public IActionResult TodoForm(Todo todo)
{
return Redirect("Index");}
}
Since we haven't connected to a database yet, we'll utilize an in-memory repository for storing todos. Create a file named TodoRepository.cs within the Models folder.
namespace FormValidation.Models;
public class TodoRepository
{
private static List<Todo> _todos = new List<Todo>();
public static IEnumerable<Todo> Todos => _todos;
public static void AddTodo(Todo todo) {
_todos.Add(todo);}
}
Next, update the TodoForm method in the HomeController to include the submitted todo item in the repository upon form submission.
[HttpPost]
public IActionResult TodoForm(Todo todo)
{
TodoRepository.AddTodo(todo);
return Redirect("Index");
}
Rendering the Todo List
To display the list of todos, we can utilize the TodoRepository in the Index method as shown below:
public IActionResult Index()
{
return View(TodoRepository.Todos);
}
In Index.cshtml, add a table to showcase the todos using a @foreach loop.
@{
Layout = null;
}
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>Todo List</h1>
<table>
<tr>
<th>Label</th>
<th>Status</th>
</tr>
@foreach (Todo todo in Model)
{
<tr>
<td>@todo.Label</td>
<td>@todo.Status</td>
</tr>
}
</table>
<a asp-action="TodoForm">Add Todo</a>
</body>
</html>
Testing the Implementation
Now, let’s ensure everything is functioning correctly. Currently, the form allows submissions with empty fields. We need to implement validations to prevent this.
Step 1: Adding Validations to the Model
using System.ComponentModel.DataAnnotations;
namespace FormValidation.Models;
public class Todo
{
[Required(ErrorMessage = "Please enter a label.")]
public string? Label { get; set; }
[Required(ErrorMessage = "Please enter a status.")]
public string? Status { get; set; }
}
Step 2: Displaying Validation Errors in the Form
<form method="post">
<label>Label:</label>
<input type="text" asp-for="Label" />
<span asp-validation-for="Label"></span>
<label>Status:</label>
<input type="text" asp-for="Status" />
<span asp-validation-for="Status"></span>
<button type="submit">Create</button>
</form>
Step 3: Updating the Controller Method
In the TodoForm method, we will leverage ModelState to check the validity of the submitted data.
[HttpPost]
public IActionResult TodoForm(Todo todo)
{
if (ModelState.IsValid) {
TodoRepository.AddTodo(todo);
return Redirect("Index");
}
return View();
}
Now, if you attempt to submit an empty form, you will receive error messages, which is the desired behavior.
Conclusion
Thank you for your interest in this guide! I hope it has been informative and helpful. If you have any feedback or comments, please feel free to share.
Now, let’s enhance our learning experience with some additional resources!
In this video titled "Form Validations In ASP.NET Core Razor Pages," you'll discover practical techniques for implementing form validations.
Watch "10 Form Validation in ASP.NET Core MVC" to learn more about effective validation strategies in MVC applications.
Feel free to connect with us on our other platforms for more insightful content!