Lesson 3: Form Submission, Model Binding, and
Validation
■ Definitions
- **Form Submission:** Sending data from a user interface (usually HTML form) to a controller. -
**Model Binding:** Automatically mapping form input values to model properties in the controller. -
**Validation:** Ensuring that form input follows rules (e.g., required fields, correct formats) before
processing.
■ Real-Time Scenario: Add Student Form
We want to allow users to add a new student to our system. The user fills in a form with details such
as Name, Age, and Email. The backend should validate the input before saving.
■ Step-by-Step Implementation
Step 1: Create Student Model
public class Student
{
public int Id { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
[Range(18, 60, ErrorMessage = "Age must be between 18 and 60")]
public int Age { get; set; }
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
}
Step 2: StudentController - Add Action Methods
public class StudentController : Controller
{
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Student student)
{
if (ModelState.IsValid)
{
// Save logic here (e.g., add to DB)
TempData["Success"] = "Student added successfully!";
return RedirectToAction("Index");
}
return View(student);
}
}
Step 3: Create.cshtml View
@model Student
<h2>Add Student</h2>
<form asp-action="Create" method="post">
<div>
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
</div>
<div>
<label asp-for="Age"></label>
<input asp-for="Age" />
<span asp-validation-for="Age"></span>
</div>
<div>
<label asp-for="Email"></label>
<input asp-for="Email" />
<span asp-validation-for="Email"></span>
</div>
<button type="submit">Submit</button>
</form>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
■ Summary
- Razor forms are submitted via POST and handled in controller actions. - Model binding auto-maps
input values to the model. - `DataAnnotations` perform validation before saving the data. - If
validation fails, form re-renders with error messages.
■ Assignments
1 1. Add a new field 'PhoneNumber' with validation (10-digit format).
2 2. Add TempData confirmation messages for success/failure cases.
3 3. Make all input fields required and display user-friendly error messages.
4 4. Improve UI using Bootstrap form controls.
5 5. Create a new form to register a Teacher with similar validation rules.