text
stringlengths
0
13.4k
The [ValidateAntiForgeryToken] attribute before the action tells
ASP.NET Core that it should look for (and verify) the hidden verification
token that was added to the form by the asp-action tag helper. This is
an important security measure to prevent cross-site request forgery
64
Add new to-do items
(CSRF) attacks, where your users could be tricked into submitting data
from a malicious site. The verification token ensures that your application
is actually the one that rendered and submitted the form.
Take a look at the AddItemPartial.cshtml view once more. The @model
TodoItem line at the top of the file tells ASP.NET Core that the view
should expect to be paired with the TodoItem model. This makes it
possible to use asp-for="Title" on the <input> tag to let ASP.NET
Core know that this input element is for the Title property.
Because of the @model line, the partial view will expect to be passed a
TodoItem object when it's rendered. Passing it a new TodoItem via
Html.PartialAsync initializes the form with an empty item. (Try
appending { Title = "hello" } and see what happens!)
During model binding, any model properties that can't be matched up
with fields in the request are ignored. Since the form only includes a
Title input element, you can expect that the other properties on
TodoItem (the IsDone flag, the DueAt date) will be empty or contain
default values.
Instead of reusing the TodoItem model, another approach would
be to create a separate model (like NewTodoItem ) that's only used
for this action and only has the specific properties (Title) you need
for adding a new to-do item. Model binding is still used, but this
way you've separated the model that's used for storing a to-do
item in the database from the model that's used for binding
incoming request data. This is sometimes called a binding model or
a data transfer object (DTO). This pattern is common in larger,
more complex projects.
After binding the request data to the model, ASP.NET Core also
performs model validation. Validation checks whether the data bound to
the model from the incoming request makes sense or is valid. You can
65
Add new to-do items
add attributes to the model to tell ASP.NET Core how it should be
validated.
The [Required] attribute on the Title property tells ASP.NET Core's
model validator to consider the title invalid if it is missing or blank. Take a
look at the code of the AddItem action: the first block checks whether
the ModelState (the model validation result) is valid. It's customary to do
this validation check right at the beginning of the action:
if (!ModelState.IsValid)
{
return RedirectToAction("Index");
}
If the ModelState is invalid for any reason, the browser will be
redirected to the /Todo/Index route, which refreshes the page.