MVC Scaffolding

ASP.NET MVC Scaffolding

Table of Contents

MVC Scaffolding is a feature of ASP.NET that allows you to generate functional code rapidly. It is also known as a code generator framework and is pre-installed in Visual Studio 2013 and a higher version.

To create a basic CRUD application, scaffolding is the best choice. It reduces time amount and generates clean code. Here, we are using scaffolding to develop a CRUD application.

ASP.NET CRUD Example

This example consists of a couple of steps that are given below.

  1. Create New Project

Select File menu from the menu bar and select New->Project. We can use the shortcut Ctrl+Shift+N also to create a new project.

MVC Scaffolding

This will pop up a window containing projects. Here, we are selecting ASP.NET Web Application.

ASP Scaffolding 2

After clicking on ok, it pops up a new window of templates. Here, we are selecting the MVC template which is used to create an MVC web application.

MVC Scaffolding

Hit ok, and then it will create a project and also shows a progress bar as shown below.

ASP Scaffolding 4

CRUD Project Structure:

MVC Scaffolding

We can run the above application by pressing Ctrl+F5 that will produce a default index page to the browser and looks like the one below.

ASP Scaffolding 6

For creating complete crud, we need to add Models, Views, and Controllers in our project. Here, we are going to create a Model that deals with the data.

1. Create a New Model

We are now creating a Student Model inside the Models folder of our project. Right-click on the Models folder and select add->class that will pop up a dialog box. Create a class by providing a name.

ASP Scaffolding 7

This model class has some source code, we can modify its code as given below.

// Student.cs
using System;  
using System.Collections.Generic;  
using System.ComponentModel.DataAnnotations;  
using System.Linq;  
using System.Web;  
namespace CrudExample.Models  
{  
public class Student  
    {  
public int ID { get; set; }  
        [Required]  
public string Name { get; set; }  
        [Required]  
        [EmailAddress]  
public string Email { get; set; }  
        [Required]  
public string Contact { get; set; }  
    }  
}   

2. Create a Context Class

We will now create another class inside the Models folder, and it is used to communicate with Entity Framework and perform database operations. This class inherits DbContext class.

// StudentRecord.cs
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Data.Entity.ModelConfiguration.Conventions;  
using System.Data.Entity;  
namespace CrudExample.Models  
{  
public class StudentRecord : DbContext  
    {  
public DbSet<Student> Students { get; set; }  
protected override void OnModelCreating(DbModelBuilder modelBuilder)  
        {  
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();  
        }  
    }  
}  

3. Add Scaffold to the Project

Right-click on the Controllers folder and add scaffold as we did in the screenshot.

ASP Scaffolding 8

It will pop up the below dialog box. Now, select controller with Entity Framework.

ASP Scaffolding 9

And click Add button. It asks for the Model and context name. Fill in the entries and click ok.

ASP Scaffolding 10

After clicking the add button, it creates a StudentsController controller and a Students folder. The Students folder contains web pages for each CRUD operation.

// StudentsController.cs
using System;  
using System.Collections.Generic;  
using System.Data;  
using System.Data.Entity;  
using System.Linq;  
using System.Net;  
using System.Web;  
using System.Web.Mvc;  
using CrudExample.Models;  
namespace CrudExample.Controllers  
{  
public class StudentsController : Controller  
    {  
private StudentRecord db = newStudentRecord();  
// GET: Students  
public ActionResult Index()  
        {  
return View(db.Students.ToList());  
        }  
// GET: Students/Details/5  
public ActionResult Details(int? id)  
        {  
if (id == null)  
            {  
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
            }  
Student student = db.Students.Find(id);  
if (student == null)  
            {  
return HttpNotFound();  
            }  
return View(student);  
        }  
// GET: Students/Create  
public ActionResult Create()  
        {  
return View();  
        }  
// POST: Students/Create  
        [HttpPost]  
        [ValidateAntiForgeryToken]  
public ActionResult Create([Bind(Include = "ID,Name,Email,Contact")] Student student)  
        {  
if (ModelState.IsValid)  
            {  
                db.Students.Add(student);  
                db.SaveChanges();  
return RedirectToAction("Index");  
            }  
return View(student);  
        }  
// GET: Students/Edit/5  
public ActionResult Edit(int? id)  
        {  
if (id == null)  
            {  
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
            }  
Student student = db.Students.Find(id);  
if (student == null)  
            {  
return HttpNotFound();  
            }  
return View(student);  
        }  
// POST: Students/Edit/5 
        [HttpPost]  
        [ValidateAntiForgeryToken]  
public ActionResult Edit([Bind(Include = "ID,Name,Email,Contact")] Student student)  
        {  
if (ModelState.IsValid)  
            {  
                db.Entry(student).State = EntityState.Modified;  
                db.SaveChanges();  
return RedirectToAction("Index");  
            }  
return View(student);  
        }  
// GET: Students/Delete/5  
public ActionResult Delete(int? id)  
        {  
if (id == null)  
            {  
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
            }  
Student student = db.Students.Find(id);  
if (student == null)  
            {  
return HttpNotFound();  
            }  
return View(student);  
        }  
// POST: Students/Delete/5  
        [HttpPost, ActionName("Delete")]  
        [ValidateAntiForgeryToken]  
public ActionResult DeleteConfirmed(int id)  
        {  
Student student = db.Students.Find(id);  
            db.Students.Remove(student);  
            db.SaveChanges();  
return RedirectToAction("Index");  
        }  
protected override void Dispose(bool disposing)  
        {  
if (disposing)  
            {  
                db.Dispose();  
            }  
base.Dispose(disposing);  
        }  
    }  
} 

The Students folder available inside the View contains the below files.

ASP Scaffolding 11

The Index.cshtml file contains the below code.

// Index.cshtml
@model IEnumerable<scaffoldingTest.Models.Student>  
@{  
    ViewBag.Title = "Index";  
}  
<h2>Index</h2>  
<p>  
    @Html.ActionLink("Create New", "Create")  
</p>  
<table class="table">  
<tr>  
<th>  
            @Html.DisplayNameFor(model => model.Name)  
</th>  
<th>  
            @Html.DisplayNameFor(model => model.Email)  
</th>  
<th>  
            @Html.DisplayNameFor(model => model.Contact)  
</th>  
<th></th>  
</tr>  
@foreach (var item in Model) {  
<tr>  
<td>  
            @Html.DisplayFor(modelItem => item.Name)  
</td>  
<td>  
            @Html.DisplayFor(modelItem => item.Email)  
</td>  
<td>  
            @Html.DisplayFor(modelItem => item.Contact)  
</td>  
<td>  
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |  
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |  
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })  
</td>  
</tr>  
}  
</table> 

Output:

Right-click on the Index.cshtml file and select “view in browser.” This will execute the file and produce the following output.

// Index file

This index file is used to show student records. Currently, the table is empty, so it does not show any data.

ASP Scaffolding 12

Add new Student

We can add a new student by clicking on the Create New button. This will redirect to a student form.

ASP Scaffolding 13

After adding it, we added two more entries then redirect them back to the index file. Now, it contains three student records.

ASP Scaffolding 14

Update Record

We can update the record by clicking on the Edit button. This will redirect to the update form. The following screenshot shows the edit page.

ASP Scaffolding 15

After updating the record, the index page looks like this:

ASP Scaffolding 16

Delete Record

We can delete any record simply by clicking on the provided Delete link. Let’s delete Roman John from the table. A confirmation message will be displayed to the user for surety.

ASP Scaffolding 17

After clicking on the Delete button, it redirects to the index page that contains the remaining records.

ASP Scaffolding 18

We can see that there are only two records are present.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article