Table of contents
1.
Introduction
2.
Creating Project of Scaffolding in ASP.NET
2.1.
Step 1: Create a new project
2.1.1.
CRUD project Structure
2.2.
Step 2: Create a new Model
2.3.
Step 3: Create a Context Class
2.4.
Step 4: Add Scaffold to the project.
3.
Output
3.1.
Add a Student
3.2.
Update Record:
3.3.
Delete Record.
4.
Frequently Asked Questions
5.
Key Takeaways
Last Updated: Mar 27, 2024

ASP.NET MVC Scaffolding

Author Naman Kukreja
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

When you visit a website or any project that provides an interface with the database, you must have noticed that some take much time to present their code in front of users for feedback. At the same time, some perform this operation very quickly. So how can we make our project do these functions quicker?

The answer is by using Scaffolding. It is used for auto-generating a set of views, models, and controllers in a single operation for a new resource.

Creating Project of Scaffolding in ASP.NET

Before directly jumping on creating a project, let us have a basic idea about Scaffolding. It is one of the main features provided by ASP.NET, with the help of which we can generate functional code rapidly.

And because of this, it is also known as the generator framework. We can use it for creating basic CRUD applications as it generates clean code and reduces time.

Step 1: Create a new project

Click on the file on the Top left side and then on new and then on project File -> New-> Project.

The above step will pop a window from which you can select the project to work, from which we are choosing ASP.NET Core with API.

It contains MVC automatically in the latest version. After that, click on ‘ok’.

CRUD project Structure

You can run it by pressing ctrl+F5. It will redirect you to the page, as shown below.

Now we need to create View, Model, Controller to complete CRUD.

Step 2: Create a new Model

Now we will create a Student Model in the Models folder. Right-click on the folder and select add-> class. It will pop a dialog box as shown below:

Click add after adding the class. Now add the following code to this class:

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 Contact { get; set; } 
public string Email { get; set; }  
        [Required]  
 
    }  
}

Step 3: Create a Context Class

Now we are creating another class inside the Models folder. IT is used to perform database operations and communicate with the Entity Framework. Enter the following code in the class:

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

Check out Entity Framework Interview Questions to know more about it.

Step 4: Add Scaffold to the project.

Now we need to add the scaffold to our project, and to do so, right-click on the controller's folder and follow the steps as done in the below-attached screenshot.

In the Student controller, add the following code:

This will pop up a dialog box like this:

Select the MVC Controller with views, using Entity Framework. Then click on add button and fill the details in the following dialog box as shown below:

This will create a student folder and a Student Controller:

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();  

 
public ActionResult Index()  
        {  
return View(db.Students.ToList());  
        }  
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);  
        }  

 
public ActionResult Create()  
        {  
return View();  
        }  
        [HttpPost]  
        [ValidateAntiForgeryToken]  
public ActionResult Create([Bind(Include = "ID,Name,Contact,Email")] Student student)  
        {  
if (ModelState.IsValid)  
            {  
                db.Students.Add(student);  
                db.SaveChanges();  
return RedirectToAction("Index");  
            }  
return View(student);  
        }  

 
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);  
        }  
 
        [HttpPost]  
        [ValidateAntiForgeryToken]  
public ActionResult Edit([Bind(Include = "ID,Name,Contact,Email")] Student student)  
        {  
if (ModelState.IsValid)  
            {  
                db.Entry(student).State = EntityState.Modified;  
                db.SaveChanges();  
return RedirectToAction("Index");  
            }  
return View(student);  
        }  
 
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);  
        }  
        [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 index.cshtml in the student folder contains the following code:

@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.Contact)  

 
    </th>  
    <th>  
        @Html.DisplayNameFor(model => model.Email)  
    </th>  
    <th></th>  
    </tr>  
    @foreach (var item in Model) {  
    <tr>  
    <td>  
                @Html.DisplayFor(modelItem => item.Name)  
    </td>  
    <td>  
        @Html.DisplayFor(modelItem => item.Contact)  

 
    </td>  
    <td>  
        @Html.DisplayFor(modelItem => item.Email)  
 
    </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> 

 

Must Read IEnumerable vs IQueryable.

Output

Now we will see the output of the project we have created. 

This is the output of the index file. Currently, the table is empty as we have not added anything.

Add a Student

Now we will add a new student by clicking on the create button:

Now add two more entries, and then the three entries will be shown in the form of a table as below:

Update Record:

You can update the record once created by clicking on the edit button below:

After updating the page, it looks like this:

Delete Record.

We can also delete a record by clicking on the Delete button. Let’s delete Harry’s entry from the table. It will display a confirmation message as follows:

After deleting, if you now check the table, it will be as follows:

We can see that only two records are present.

Frequently Asked Questions

1. Write the advantage of Scaffolding over methods like list, show, etc.?

Answer: We do not have to create all these methods while working with Scaffolding. It does all this work for us.

2. Write some benefits of Scaffolding?

Answer: Can quickly get in front of users for feedback and write the code more cleanly and faster.

3. What is the difference between both static and dynamic Scaffolding?

Answer: Static Scaffolding needs user insertion commands to generate data fields, whereas Dynamic Scaffolding generates the entire content at run time.

4. Can we perform Scaffolding in every version of Visual Studio?

Answer: No, it will only work in the versions 2013 and above.

Key Takeaways

In this blog, we have learned about Scaffolding in ASP.NET and how to create projects using Scaffolding in Visual Code with proper steps and output.

Recommended Readings:

Apart from this, you can also expand your knowledge by referring to these articles on Features Of ASP Net and ASP Full Form.

Refer to this blog if you want to learn about MVC Validations in ASP.NET. You will have a complete idea about MVC validations with basic annotations and all these with suitable examples.

Live masterclass