ASP Dot Net Scaffold a Controller and Views for CRUD Operations

Mohamad MahmoodMohamad Mahmood
3 min read

continue from https://hashnotes.hashnode.dev/asp-dot-net-with-entityframeworkcore

Scaffold a Controller and Views for CRUD Operations

Now that your SQLite database is created and working, it's time to build the user interface for managing blog posts.

We'll scaffold:

  • A controller (BlogController)

  • Razor views for:

    • Listing all blog posts

    • Creating new ones

    • Viewing details

    • Editing and deleting

Step 1: Create the BlogController

Add the following codes to Controller/BlogControllers.cs:

using Microsoft.AspNetCore.Mvc;
using MyMvcApp.Data;
using MyMvcApp.Models;

namespace MyMvcApp.Controllers
{
    public class BlogController : Controller
    {
        private readonly AppDbContext _context;

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

        // GET: /Blog
        public IActionResult Index()
        {
            var posts = _context.BlogPosts.ToList();
            return View(posts);
        }

        // GET: /Blog/Details/5
        public IActionResult Details(int? id)
        {
            if (id == null)
                return NotFound();

            var post = _context.BlogPosts.Find(id);
            if (post == null)
                return NotFound();

            return View(post);
        }

        // GET: /Blog/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: /Blog/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(BlogPost post)
        {
            if (ModelState.IsValid)
            {
                _context.BlogPosts.Add(post);
                _context.SaveChanges();
                return RedirectToAction(nameof(Index));
            }
            return View(post);
        }

        // GET: /Blog/Edit/5
        public IActionResult Edit(int? id)
        {
            if (id == null)
                return NotFound();

            var post = _context.BlogPosts.Find(id);
            if (post == null)
                return NotFound();

            return View(post);
        }

        // POST: /Blog/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(int id, BlogPost post)
        {
            if (id != post.Id)
                return NotFound();

            if (ModelState.IsValid)
            {
                _context.BlogPosts.Update(post);
                _context.SaveChanges();
                return RedirectToAction(nameof(Index));
            }
            return View(post);
        }

        // GET: /Blog/Delete/5
        public IActionResult Delete(int? id)
        {
            if (id == null)
                return NotFound();

            var post = _context.BlogPosts.Find(id);
            if (post == null)
                return NotFound();

            return View(post);
        }

        // POST: /Blog/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteConfirmed(int id)
        {
            var post = _context.BlogPosts.Find(id);
            if (post != null)
            {
                _context.BlogPosts.Remove(post);
                _context.SaveChanges();
            }
            return RedirectToAction(nameof(Index));
        }
    }
}

Step 2: Create the Views Folder

mkdir -p Views/Blog

Step 3: Add Razor Views

Views/Blog/Index.cshtml

@model IEnumerable<MyMvcApp.Models.BlogPost>

@{
    ViewData["Title"] = "Blog Posts";
}

<h2>Blog Posts</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>

<table class="table">
    <thead>
        <tr>
            <th>Title</th>
            <th>Date</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.Title</td>
                <td>@item.CreatedAt.ToShortDateString()</td>
                <td>
                    <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                    <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                    <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>

Views/Blog/Create.cshtml

@model MyMvcApp.Models.BlogPost

@{
    ViewData["Title"] = "Create Post";
}

<h2>Create New Blog Post</h2>

<form asp-action="Create">
    <div class="form-group">
        <label asp-for="Title"></label>
        <input asp-for="Title" class="form-control" />
        <span asp-validation-for="Title" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Content"></label>
        <textarea asp-for="Content" class="form-control" rows="5"></textarea>
        <span asp-validation-for="Content" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-primary">Save</button>
</form>

Views/Blog/Edit.cshtml

@model MyMvcApp.Models.BlogPost

@{
    ViewData["Title"] = "Edit Post";
}

<h2>Edit Blog Post</h2>

<form asp-action="Edit">
    <input type="hidden" asp-for="Id" />
    <div class="form-group">
        <label asp-for="Title"></label>
        <input asp-for="Title" class="form-control" />
        <span asp-validation-for="Title" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Content"></label>
        <textarea asp-for="Content" class="form-control" rows="5"></textarea>
        <span asp-validation-for="Content" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-primary">Update</button>
</form>

Views/Blog/Details.cshtml

@model MyMvcApp.Models.BlogPost

@{
    ViewData["Title"] = "Post Details";
}

<h2>@Model.Title</h2>

<div>
    <p><strong>Created:</strong> @Model.CreatedAt</p>
    <p>@Model.Content</p>
</div>

<p>
    <a asp-action="Edit" asp-route-id="@Model.Id">Edit</a> |
    <a asp-action="Index">Back to List</a>
</p>

Views/Blog/Delete.cshtml

@model MyMvcApp.Models.BlogPost

@{
    ViewData["Title"] = "Delete Post";
}

<h2>Are you sure you want to delete this?</h2>

<div>
    <h4>@Model.Title</h4>
    <p>@Model.Content</p>
</div>

<form asp-action="DeleteConfirmed" method="post">
    <input type="hidden" asp-for="Id" />
    <button type="submit" class="btn btn-danger">Delete</button>
    <a asp-action="Index" class="btn btn-secondary">Cancel</a>
</form>

Step 4: Run the Application

In the terminal, run:

dotnet watch run --urls=http://0.0.0.0:8080
0
Subscribe to my newsletter

Read articles from Mohamad Mahmood directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mohamad Mahmood
Mohamad Mahmood

Mohamad's interest is in Programming (Mobile, Web, Database and Machine Learning). He studies at the Center For Artificial Intelligence Technology (CAIT), Universiti Kebangsaan Malaysia (UKM).