In this lesson, we'll add more CRUD functionality to our to do list using our new Entity-powered ORM capabilities. Specifically, we'll focus on the create action here.
Creating a new task 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. However, because of the way that HTML helper methods streamline our forms, this new format will be necessary for the time being.
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 method we run on our DBSet
property of our DBContext
, while SaveChanges()
is a method we run on the DBContext
itself.
Together, they update the DBSet
and then sync those changes to the database which the DBContext
represents. Once again, Entity 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.
Follow the link below to view how a sample version of the project should look at this point. Note that this is a link to a specific commit in the repository.
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");
}
}
}
Lesson 24 of 36
Last updated more than 3 months ago.