ASP.NET Core MVC Beginner

Building forms with Tag Helpers

Forms are how users send data to your app. This lesson builds a complete form with Tag Helpers: the form, labels, inputs, a drop-down and validation messages, plus the GET and POST actions that show and process it.

The life of a form
  1. StartGET shows the formThe GET action returns the view with an empty model
  2. Step 2User submitsThe browser POSTs the fields and the anti-forgery token
  3. Step 3Bind and validateModel binding fills the model; rules are checked
  4. Step 4Invalid?Return the same view; Tag Helpers show the messages
  5. Step 5ValidSave the data, then redirect (Post-Redirect-Get)
  6. EndConfirmation pageA GET request shows the result; refresh is safe

The idea in plain words

With Tag Helpers you bind each form element to a model property using asp-for. The Tag Helper writes the right name, id, type and current value, and adds validation attributes based on your data annotations. The form Tag Helper builds the action URL from routing and adds a hidden anti-forgery token automatically.

Example: the view

Razor
@model ContactModel
<form asp-controller="Contact" asp-action="Send" method="post">
    <div asp-validation-summary="ModelOnly"></div>

    <label asp-for="Name"></label>
    <input asp-for="Name" />
    <span asp-validation-for="Name"></span>

    <label asp-for="Topic"></label>
    <select asp-for="Topic" asp-items="Model.Topics"></select>

    <label asp-for="Message"></label>
    <textarea asp-for="Message"></textarea>
    <span asp-validation-for="Message"></span>

    <button type="submit">Send</button>
</form>

@section Scripts { <partial name="_ValidationScriptsPartial" /> }

Example: the actions and model

One action shows the form and another processes it. After a successful POST, redirect so refreshing the page does not send the form again.

C#
public class ContactModel
{
    [Required] public string Name { get; set; } = "";
    [Required, StringLength(1000)] public string Message { get; set; } = "";
    public string Topic { get; set; } = "General";
    public List<SelectListItem> Topics { get; } =
        new() { new("General", "General"), new("Billing", "Billing") };
}

public class ContactController : Controller
{
    [HttpGet]
    public IActionResult Send() => View(new ContactModel());

    [HttpPost, ValidateAntiForgeryToken]
    public IActionResult Send(ContactModel model)
    {
        if (!ModelState.IsValid) return View(model);
        // send or store the message...
        TempData["Status"] = "Thanks, we got your message.";
        return RedirectToAction(nameof(Send));
    }
}

Common mistakes

  • Writing name attributes by hand that do not match the model, so values never bind.
  • Returning View() after a successful POST instead of redirecting.
  • Forgetting [ValidateAntiForgeryToken] on POST actions (or a global filter).
  • Losing drop-down items when redisplaying an invalid form because they were not repopulated.

Interview question

What is the Post-Redirect-Get pattern and why use it?

After a form POST succeeds, the server responds with a redirect to a GET page instead of rendering a view directly. The browser then loads that page with a GET request. If the user refreshes, only the GET is repeated, so the form is not submitted twice, and the URL in the address bar points to a page that is safe to bookmark.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.