Introduction
In the previous lesson, we worked with the Razor View Engine, layouts, and reusable interface components. Our application now needs to receive data from users. In the content management application, a user should be able to enter a title, summary, body, and category to create a new content item.
This may look simple, but web forms must be designed carefully for both security and maintainability. Binding a form directly to a database entity can allow clients to submit fields they should not control. This issue is commonly known as overposting. In this lesson, we will place a dedicated ViewModel between the form and the entity.
By the end of the lesson, you will understand model binding, create a ViewModel containing only the fields required by the form, implement GET and POST actions, add validation and CSRF protection, and redisplay invalid forms safely.
What is model binding?
ASP.NET Core MVC converts key-value pairs from an HTTP request into action parameters or model properties. This process is called model binding. For example, if a form contains an input named Title and the POST action accepts a CreateContentViewModel parameter, MVC attempts to assign the input value to the ViewModel's Title property.
[HttpPost]
public IActionResult Create(CreateContentViewModel model)
{
// model.Title comes from the form field name="Title".
return View(model);
}Names are important during binding. The Razor expression asp-for="Title" normally generates an input with name="Title". Model binding uses that name to locate the matching property. If the field name does not match the ViewModel property, the value may not be bound.
Model binding is not limited to form values. Query-string values, route values, form fields, headers, and other supported sources can also be used. Attributes such as [FromRoute], [FromQuery], and [FromForm] can make the source explicit. For a conventional MVC form, however, a model parameter and matching form fields are often sufficient.
Using a ViewModel instead of an entity
Assume that the database entity in our application looks like this:
public class Content
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Slug { get; set; } = string.Empty;
public string Summary { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public bool IsPublished { get; set; }
public DateTime CreatedAt { get; set; }
public string? AuthorId { get; set; }
public int CategoryId { get; set; }
}This entity represents the database structure. The create form does not need to accept every property. Values such as Id, CreatedAt, AuthorId, and Slug should not be supplied by the client or trusted directly. Therefore, we create a ViewModel dedicated to the form.
using System.ComponentModel.DataAnnotations;
public class CreateContentViewModel
{
[Required(ErrorMessage = "Title is required.")]
[StringLength(120, MinimumLength = 3,
ErrorMessage = "Title must be between 3 and 120 characters.")]
[Display(Name = "Title")]
public string Title { get; set; } = string.Empty;
[Required(ErrorMessage = "Summary is required.")]
[StringLength(300, ErrorMessage = "Summary cannot exceed 300 characters.")]
[Display(Name = "Summary")]
public string Summary { get; set; } = string.Empty;
[Required(ErrorMessage = "Body is required.")]
[MinLength(20, ErrorMessage = "Body must contain at least 20 characters.")]
[Display(Name = "Body")]
public string Body { get; set; } = string.Empty;
[Range(1, int.MaxValue, ErrorMessage = "Select a valid category.")]
[Display(Name = "Category")]
public int CategoryId { get; set; }
[Display(Name = "Publish now")]
public bool PublishNow { get; set; }
}The ViewModel transports only the data required by this form. Even if a client submits fields such as IsPublished, AuthorId, or CreatedAt, those fields are not part of the action parameter and are therefore not bound to it.
Preparing the controller actions
First, display the form with a GET action. In this lesson, we can use ViewBag for the category list. In later lessons, we will also place select options inside a strongly typed ViewModel. In production applications, the strongly typed approach is generally easier to maintain because it provides stronger metadata and compile-time support.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
public class ContentsController : Controller
{
private readonly ApplicationDbContext _context;
public ContentsController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet]
public IActionResult Create()
{
ViewBag.Categories = new SelectList(
_context.Categories.OrderBy(c => c.Name).ToList(),
"Id",
"Name");
return View(new CreateContentViewModel());
}
}The POST action receives the form data. The first step is to inspect the result of model binding and validation.
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(CreateContentViewModel model)
{
if (!ModelState.IsValid)
{
ViewBag.Categories = new SelectList(
_context.Categories.OrderBy(c => c.Name).ToList(),
"Id",
"Name",
model.CategoryId);
return View(model);
}
var content = new Content
{
Title = model.Title.Trim(),
Summary = model.Summary.Trim(),
Body = model.Body.Trim(),
CategoryId = model.CategoryId,
IsPublished = model.PublishNow,
CreatedAt = DateTime.UtcNow,
AuthorId = User.Identity?.Name
};
content.Slug = CreateSlug(content.Title);
_context.Contents.Add(content);
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}The important point is that the conversion from the ViewModel to the entity is explicit. This requires a little more code, but it makes the list of persisted fields visible. Instead of accepting an entity directly, the action performs a controlled mapping.
Creating the Razor form
Specify the ViewModel in Views/Contents/Create.cshtml:
@model CreateContentViewModel
<h2>New Content</h2>
<form asp-controller="Contents" asp-action="Create" method="post">
<div>
<label asp-for="Title"></label>
<input asp-for="Title" />
<span asp-validation-for="Title"></span>
</div>
<div>
<label asp-for="Summary"></label>
<textarea asp-for="Summary"></textarea>
<span asp-validation-for="Summary"></span>
</div>
<div>
<label asp-for="Body"></label>
<textarea asp-for="Body" rows="10"></textarea>
<span asp-validation-for="Body"></span>
</div>
<div>
<label asp-for="CategoryId"></label>
<select asp-for="CategoryId" asp-items="ViewBag.Categories">
<option value="0">Select a category</option>
</select>
<span asp-validation-for="CategoryId"></span>
</div>
<div>
<input asp-for="PublishNow" />
<label asp-for="PublishNow"></label>
</div>
<button type="submit">Save</button>
</form>The Form Tag Helper generates the action URL and can generate an antiforgery token for use with MVC's antiforgery validation. The Input, Label, and Validation Tag Helpers use ViewModel metadata to produce appropriate HTML, id, name, and validation attributes.
ModelState and the validation flow
Conversion errors during model binding and validation errors are stored in ModelState. For example, if text is submitted for CategoryId, or if the title is empty, ModelState.IsValid becomes false.
When validation fails, return the same ViewModel to the view. This preserves the user's input and allows validation messages to be displayed. However, supporting data such as category options must be rebuilt before returning the view. Otherwise, the select element may be empty or the view may fail to render.
Server-side validation is always required. HTML5 and JavaScript validation improve the user experience, but a malicious client can bypass them. The actual security boundary is server-side validation in the controller or application service.
Antiforgery and secure POST requests
A form on another site may try to make a user's browser send a request to your application. This attack is known as CSRF or XSRF. Adding [ValidateAntiForgeryToken] to the POST action requires the request to contain a token generated by the application.
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(CreateContentViewModel model)
{
// validation and persistence logic
return View(model);
}When you use the Form Tag Helper, the token can be generated automatically. If you write a plain HTML form, you can add @Html.AntiForgeryToken() to the Razor view. POST, PUT, PATCH, and DELETE operations that change data should receive special attention from a CSRF protection perspective.
Understanding overposting
The following approach is risky:
[HttpPost]
public IActionResult Create(Content content)
{
_context.Contents.Add(content);
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}This action binds many entity properties directly from client input. A malicious user could submit hidden fields such as IsPublished, AuthorId, or another property and cause the application to persist values that should have been controlled by the server.
The [Bind] attribute can restrict bindable fields in some create scenarios, but a separate ViewModel is usually clearer and safer for long-term maintenance. It separates the form contract from the entity. It also prevents a newly added entity property from automatically becoming accepted by every form.
Generating a slug and distrusting client input
A slug can be generated on the server instead of being accepted directly from the user. A simple example is:
private static string CreateSlug(string value)
{
var slug = value.Trim().ToLowerInvariant();
slug = string.Join("-", slug.Split(' ', StringSplitOptions.RemoveEmptyEntries));
return slug;
}In a real project, Turkish characters, punctuation, URL conventions, uniqueness, and normalization require additional decisions. You should check slug uniqueness and define a strategy for duplicate titles. User input should not be emitted as raw HTML; preserve Razor's default HTML encoding behavior.
Common mistakes
- Using the entity as the POST parameter: This can bind unnecessary properties and create an overposting risk.
- Trusting only client-side validation: Server-side validation must always be performed.
- Failing to rebuild supporting data: Select lists may be empty when an invalid form is redisplayed.
- Returning the same view after a successful POST: Refreshing the page may submit the form again. Use the Redirect-After-Post pattern after a successful operation.
- Accepting timestamps and user identity from the client: Values such as
CreatedAtandAuthorIdshould be determined on the server. - Forgetting antiforgery protection: Form actions that change data should validate an antiforgery token.
Short practice exercise
Extend the form from this lesson with the following exercise:
- Add a
MetaDescriptionproperty with a maximum length of 160 characters toCreateContentViewModel. - Add an input and validation message to the Razor view.
- Map the value to the entity in the POST action.
- Test an empty title, an overlong summary, and an invalid category.
- Inspect the
nameattributes of the input elements in the browser developer tools. - Try submitting an extra
IsPublishedfield manually and confirm that it is not bound to the ViewModel.
Conclusion
In this lesson, we used a ViewModel to separate user input from the database entity. We saw how model binding maps form fields to ViewModel properties. We added basic validation rules with data annotations, checked the server-side result with ModelState.IsValid, and rebuilt supporting data before redisplaying an invalid form.
We also examined antiforgery tokens, overposting, server-controlled fields, and the Redirect-After-Post pattern. In the next step, we will persist the form data with Entity Framework Core and examine the category relationship in more detail.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-8.0
- https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-8.0
- https://learn.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-8.0
- https://learn.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-8.0