text
stringlengths 0
13.4k
|
|---|
<button type="submit">Add</button>
|
</form>
|
The asp-action tag helper can generate a URL for the form, just like
|
when you use it on an <a> element. In this case, the asp-action helper
|
gets replaced with the real path to the AddItem route you'll create:
|
<form action="/Todo/AddItem" method="POST">
|
Adding an asp- tag helper to the <form> element also adds a hidden
|
field to the form containing a verification token. This verification token
|
can be used to prevent cross-site request forgery (CSRF) attacks. You'll
|
verify the token when you write the action.
|
That takes care of creating the partial view. Now, reference it from the
|
main Todo view:
|
Views/Todo/Index.cshtml
|
<div class="panel-footer add-item-form">
|
@await Html.PartialAsync("AddItemPartial", new TodoItem())
|
</div>
|
Add an action
|
When a user clicks Add on the form you just created, their browser will
|
construct a POST request to /Todo/AddItem on your application. That
|
won't work right now, because there isn't any action that can handle the
|
/Todo/AddItem route. If you try it now, ASP.NET Core will return a 404
|
Not Found error.
|
63
|
Add new to-do items
|
You'll need to create a new action called AddItem on the
|
TodoController :
|
[ValidateAntiForgeryToken]
|
public async Task<IActionResult> AddItem(TodoItem newItem)
|
{
|
if (!ModelState.IsValid)
|
{
|
return RedirectToAction("Index");
|
}
|
var successful = await _todoItemService.AddItemAsync(newItem);
|
if (!successful)
|
{
|
return BadRequest("Could not add item.");
|
}
|
return RedirectToAction("Index");
|
}
|
Notice how the new AddItem action accepts a TodoItem parameter?
|
This is the same TodoItem model you created in the MVC basics chapter
|
to store information about a to-do item. When it's used here as an action
|
parameter, ASP.NET Core will automatically perform a process called
|
model binding.
|
Model binding looks at the data in a request and tries to intelligently
|
match the incoming fields with properties on the model. In other words,
|
when the user submits this form and their browser POSTs to this action,
|
ASP.NET Core will grab the information from the form and place it in the
|
newItem variable.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.