Adding Validation, Layouts, and Improved UI Using Bootstrap
In Part 1, you built a complete CRUD module for Products using ASP.NET Core MVC with Controllers, Models, and Views.
In Part 2, you will enhance the project by adding:
Form validation (server-side + client-side)
A shared layout (
_Layout.cshtml)Bootstrap-based clean UI
This is where your app starts looking like a real-world MVC project.
1. Adding Model Validation
ASP.NET Core uses data annotations for validation.
Update your Product.cs model:
using System.ComponentModel.DataAnnotations;
namespace MVCApp.Models
{
public class Product
{
public int Id { get; set; }
[Required(ErrorMessage = "Product name is required")]
[StringLength(100)]
public string Name { get; set; }
[Range(1, 100000, ErrorMessage = "Price must be greater than 0")]
public decimal Price { get; set; }
}
}
✔ What this adds
Required validation
Custom error messages
Client-side validation automatically enabled
2. Update Create View With Validation
Views/Product/Create.cshtml
@model MVCApp.Models.Product
<h2>Add New Product</h2>
<form asp-action="Create" method="post">
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Price"></label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
<br />
<button type="submit" class="btn btn-success">Save</button>
</form>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
3. Update Edit View With Validation
Views/Product/Edit.cshtml
@model MVCApp.Models.Product
<h2>Edit Product</h2>
<form asp-action="Edit" method="post">
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Price"></label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
<br />
<button type="submit" class="btn btn-primary">Update</button>
</form>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Join the conversation! Your thoughts help the community grow.