9. Forms and Tag Helpers
Tag helpers are special attributes that add server-side behaviour to HTML tags. They make forms and links easier and less error-prone than writing URLs by hand. Enable them in Views/_ViewImports.cshtml. A form normally has two actions: a GET that shows the empty form and a POST that receives the submitted data.
Key points
- asp-controller and asp-action build links and form targets.
- asp-for connects an input to a model property.
- asp-validation-for shows the validation message for a property.
- Always add the [HttpPost] attribute to the action that receives the form.
- Use @Html.AntiForgeryToken() or rely on the form tag helper to protect against CSRF.
Example: Create form (view)
@model Student
<form asp-controller="Students" asp-action="Create" method="post">
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
<label asp-for="Age"></label>
<input asp-for="Age" />
<span asp-validation-for="Age"></span>
<button type="submit">Save</button>
</form>
Show explanation
The input names and ids are generated from the model, and validation messages appear next to the right field.
Example: Create actions (controller)
[HttpGet]
public IActionResult Create() => View();
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Student student)
{
if (!ModelState.IsValid)
return View(student); // show the form again with errors
// save student...
return RedirectToAction(nameof(Index));
}
Show explanation
If validation fails the same form is shown with the user's values and error messages. If it passes the student is saved and the user is redirected.