Lesson Sunday

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.

Create


Creating a new task is a two-step process:

  1. We need a form to supply information about the new task.
  2. We also need functionality to submit that form and save the information it contains to our database.

This means we'll also need two Create actions:

  1. A GET action to display our form to users.
  2. A POST action to manage form submission.

Controller

Let's add these actions to our ItemsController now:

ItemsController.cs
...
public ActionResult Create()
{
    return View();
}

[HttpPost]
public ActionResult Create(Item item)
{
    _db.Items.Add(item);
    _db.SaveChanges();
    return RedirectToAction("Index");
}
...
  1. 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.

  2. 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.

Repository Reference

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.

Example GitHub Repo for To Do List

Controllers/ItemsController.cs

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.