In this lesson, we'll add more CRUD functionality to our To Do List using our new EF Core-powered ORM capabilities. Specifically, we'll focus on the create action here.
Creating a new item is a two-step process:
This means we'll also need two Create
actions:
GET
action to display our form to users.POST
action to manage form submission.Let's add these actions to our ItemsController
now:
...
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Item item)
{
_db.Items.Add(item);
_db.SaveChanges();
return RedirectToAction("Index");
}
...
The Create()
GET
route is used exactly the same way as New()
was before we started using Entity. You may notice that this strays from our RESTful routing practices — previously, we learned that New()
should be used for this GET
request. We are now straying from our RESTful routing practices in order to make use of new tools that streamline our forms: HTML helper methods. We will go into depth about HTML helper methods in the next lesson.
The second action is our POST
request. This route will take an item
as an argument, add it to the Items
DbSet
, and then save the changes to our database object. Afterwards, it will redirect users to the Index
view.
Add()
is a DbSet
method we run on our DBSet
property of our ToDoListContext
, while SaveChanges()
is a DbContext
method that we run on the ToDoListContext
itself (which extends the DbContext
class).
Together, they update the DBSet
and then sync those changes to the database which the ToDoListContext
represents. Once again, EF Core takes care of the work for us.
In the next lesson, we'll learn about HTML helper methods, which will make it much easier to create forms and simplify our HTML.
using Microsoft.AspNetCore.Mvc;
using ToDoList.Models;
using System.Collections.Generic;
using System.Linq;
namespace ToDoList.Controllers
{
public class ItemsController : Controller
{
private readonly ToDoListContext _db;
public ItemsController(ToDoListContext db)
{
_db = db;
}
public ActionResult Index()
{
List<Item> model = _db.Items.ToList();
return View(model);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Item item)
{
_db.Items.Add(item);
_db.SaveChanges();
return RedirectToAction("Index");
}
}
}