1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【ASP.NET初心者が学んでみた】第5章:編集・削除機能を追加してみる 〜 CRUD操作の完成 〜

1
Posted at

🏁 はじめに

前回(第4章:ModelとDatabaseを繋げてみる)では、
Entity Framework Core(EF Core)を使ってデータを保存・一覧表示できるようにしました。

今回は、いよいよCRUD操作の後半、更新(Edit)と削除(Delete) を追加して、
Webアプリらしい「Todo管理システム」を完成させます💪

🎯 今回のゴール

一覧から「編集」「削除」ができるようにする

最終的にこうなります👇

[ Todo一覧 ]
1. 買い物に行く [編集] [削除]
2. 勉強する   [編集] [削除]

🧩 Step 1:ルーティングの理解

既に /TodosIndex/Todos/Create のように動いています。
今後は以下のルートが追加されます。

機能 URL HTTPメソッド
編集フォーム表示 /Todos/Edit/1 GET
編集内容の送信 /Todos/Edit/1 POST
削除確認画面表示 /Todos/Delete/1 GET
削除実行 /Todos/DeleteConfirmed/1 POST

⚙️ Step 2:TodosControllerに編集機能を追加

using Microsoft.AspNetCore.Mvc;
using MyFirstAspNetApp.Models;

namespace MyFirstAspNetApp.Controllers
{
    public class TodosController : Controller
    {
        private readonly AppDbContext _context;

        public TodosController(AppDbContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            var todos = _context.Todos.ToList();
            return View(todos);
        }

        // --- 編集機能 ---
        [HttpGet]
        public IActionResult Edit(int id)
        {
            var todo = _context.Todos.Find(id);
            if (todo == null) return NotFound();
            return View(todo);
        }

        [HttpPost]
        public IActionResult Edit(Todo todo)
        {
            if (ModelState.IsValid)
            {
                _context.Todos.Update(todo);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(todo);
        }

        // --- 削除機能 ---
        [HttpGet]
        public IActionResult Delete(int id)
        {
            var todo = _context.Todos.Find(id);
            if (todo == null) return NotFound();
            return View(todo);
        }

        [HttpPost, ActionName("DeleteConfirmed")]
        public IActionResult DeleteConfirmed(int id)
        {
            var todo = _context.Todos.Find(id);
            if (todo != null)
            {
                _context.Todos.Remove(todo);
                _context.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        // 新規作成
        [HttpGet]
        public IActionResult Create() => View();

        [HttpPost]
        public IActionResult Create(Todo todo)
        {
            if (ModelState.IsValid)
            {
                _context.Todos.Add(todo);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(todo);
        }
    }
}

🧾 Step 3:Viewを追加

Views/Todos/Edit.cshtml

@model MyFirstAspNetApp.Models.Todo

<h2>編集</h2>

<form asp-action="Edit" method="post">
    <input type="hidden" asp-for="Id" />
    <div>
        <label asp-for="Title"></label><br />
        <input asp-for="Title" />
        <span asp-validation-for="Title" class="text-danger"></span>
    </div>
    <button type="submit">更新</button>
</form>
<p><a href="/Todos">戻る</a></p>

Views/Todos/Delete.cshtml

@model MyFirstAspNetApp.Models.Todo

<h2>削除確認</h2>
<p>以下のTodoを削除しますか?</p>

<p><strong>@Model.Title</strong></p>

<form asp-action="DeleteConfirmed" method="post">
    <input type="hidden" asp-for="Id" />
    <button type="submit">削除</button>
    <a href="/Todos">キャンセル</a>
</form>

Views/Todos/Index.cshtml の修正

編集・削除ボタンを追加します。

@model IEnumerable<MyFirstAspNetApp.Models.Todo>

<h2>Todo一覧</h2>
<p><a href="/Todos/Create">新規作成</a></p>

<table class="table">
    <thead>
        <tr>
            <th>ID</th>
            <th>タイトル</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.Id</td>
            <td>@item.Title</td>
            <td>
                <a href="/Todos/Edit/@item.Id">編集</a> |
                <a href="/Todos/Delete/@item.Id">削除</a>
            </td>
        </tr>
    }
    </tbody>
</table>

▶ Step 4:実行してみる!

  1. /Todos へアクセスして一覧を表示
  2. 「編集」を押してタイトルを変更 → 保存
  3. 「削除」を押して確認 → 削除

🎉 CRUD(Create, Read, Update, Delete)すべてが完成しました!

✅ まとめ

操作 関連メソッド Viewファイル
登録 Create() Create.cshtml
一覧表示 Index() Index.cshtml
編集 Edit() Edit.cshtml
削除 Delete() / DeleteConfirmed() Delete.cshtml

💬 学んでみて感じたこと

  • ASP.NET MVCの構造は非常に明確(Controller→View→Model)
  • [HttpGet][HttpPost] のペアで操作を分けるのが自然
  • EF CoreのおかげでSQLを意識せずCRUDが完成するのは本当に便利!

「Controllerにロジック、ViewにUI、Modelにデータ」
これさえ守れば迷わない。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?