Skip to content
Related Articles

Related Articles

ASP.NET MVC Scaffolding

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 22 Mar, 2022

Scaffolding is used to define the code-generation framework used in web applications. It uses T4 templates to generate basic controllers and views for the models. It generates instances for the mapped domain model and code for all CRUD operations. It also reduces the amount of time for developing a standard data operation in the application.

Basically, it is an automated code generation framework, it generates code for CRUD operations based on the provided domain model classes and DB connections. You can add scaffolding to your project when you want to add code that interacts with the data model in the shortest amount of time.

In this article, we will see how to use ASP.NET MVC 4 scaffolding to automatically generate an application’s CRUD (Create, Read, Update and Delete) for our application. Simply start with write model class, and without writing the code, 

You will create a controller with the help of scaffolding that contains all the CRUD operations, as well as all the necessary views. 

In this exercise, you will learn how to use ASP.NET MVC 4 scaffolding with code first approach to create the CRUD methods.

Let’s get started,

Step 1: First, we simply create an MVC application. Open the VS >> Enter the name for application >> select MVC template then click on create. In our case ToDo_ListApplication

Step 2: Add the model class i.e ToDoListModel

C#




using System.ComponentModel.DataAnnotations;
  
namespace ToDo_ListApplication.Models
{
    public class ToDOListModel
    {
        public int Id { get; set; }
        [Required]
        [MaxLength(50)]
        public string Note { get; set; }
  
    }
}

Step 3: Install EntityFramework and then Create a new folder with the name ApplicationDbContext then add a new class called “ToDoDbContext” that inherits the DbContext class and create a DbSet property i.e ToDoList so that our EF can recognize it as an entity.

C#




using System.Data.Entity;
  
namespace ToDo_ListApplication.Models
{
    public class ToDoDbContext : DbContext
    {
        public ToDoDbContext() : base("ToDoContextDemo")
        {
  
        }
        public DbSet<ToDOListModel> ToDoList { get; set; }
    }
}

As you can see in the above code i.e ToDoContextDemo is the connection string name that I have added in the web.config file.

Now the next most important thing to remember before creating scaffolding is to Build our Project and make sure it compiles without an error. if you try without building the solution then you will get the below error popup. so be sure before creating scaffolding to build the solution.

Step 2: Now let’s create scaffolding,

In the Solution Explorer, right-click the controller’s folder and select Add | New scaffolded item.

Template: Choose “MVC with read/write actions and views, using Entity Framework” as a template. It will do the magic of creating code for all CRUD Operations/Actions and Views automatically.

After clicking on create it ask you for,

  1. Model class: Entity needs to be mapped to a specific model class, here in our case, it’s ToDOListModel.
  2. Data context class: Choose the DbContext class where the ToDo model is been referred In our case ToDoDbContext and
  3. Controller Name: Add name In our case ToDoController click on “Add“.

After creating the ToDoController controller with scaffolding

Open ToDoController class. see that the full CRUD action methods have been generated automatically.

You can see that “ToDoController ” is auto-generated with DbContext instantiation i.e db and basic action results. 

Example: The index() action that returns a view where it injects a list of ToDoList retrieved from the Entity Framework database. If you look at the code inside the index() method that gets the list.

C#




using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using ToDo_ListApplication.Models;
  
namespace ToDo_ListApplication.Controllers
{
    public class ToDoController : Controller
    {
        private ToDoDbContext db = new ToDoDbContext();
  
        // GET: ToDo
        public ActionResult Index()
        {
            return View(db.ToDoList.ToList());
        }
  
        // GET: ToDo/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ToDOListModel toDOListModel = db.ToDoList.Find(id);
            if (toDOListModel == null)
            {
                return HttpNotFound();
            }
            return View(toDOListModel);
        }
  
        // GET: ToDo/Create
        public ActionResult Create()
        {
            return View();
        }
  
        // POST: ToDo/Create
        // To protect from overposting attacks, enable the 
        // specific properties you want to bind to
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(
            [Bind(Include = "Id,Note")] 
            ToDOListModel toDOListModel)
        {
            if (ModelState.IsValid)
            {
                db.ToDoList.Add(toDOListModel);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
  
            return View(toDOListModel);
        }
  
        // GET: ToDo/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ToDOListModel toDOListModel = db.ToDoList.Find(id);
            if (toDOListModel == null)
            {
                return HttpNotFound();
            }
            return View(toDOListModel);
        }
  
        // POST: ToDo/Edit/5
        // To protect from overposting attacks, enable the 
        // specific properties you want to bind to, for 
          
        // more details see:
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(
            [Bind(Include = "Id,Note")] 
            ToDOListModel toDOListModel)
        {
            if (ModelState.IsValid)
            {
                db.Entry(toDOListModel).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(toDOListModel);
        }
  
        // GET: ToDo/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ToDOListModel toDOListModel = db.ToDoList.Find(id);
            if (toDOListModel == null)
            {
                return HttpNotFound();
            }
            return View(toDOListModel);
        }
  
        // POST: ToDo/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            ToDOListModel toDOListModel = db.ToDoList.Find(id);
            db.ToDoList.Remove(toDOListModel);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
  
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

The scaffolding engine also creates the views required for CRUD as shown in the below image.i.e Create, Delete, Details, Edit and Index.

For instance, the view Create.cshtml generates codes such as referring to the model

@model ToDo_ListApplication.Models.ToDOListModel

And creates an Html form and fields using Razor’s Html Helpers

As the same for other operations, you can see auto-generated view code. In the view folder.  

Your application is ready, now you can lunch the application.

Let’s run the application: In the browser, add your controller name In our case /ToDo to the URL to open the ToDo page.

You will now explore the ToDo pages and test the CRUD operations.

  • Adding a new person: Click Create New to add a new ToDo.

  • ToDo details: Click Details to open the ToDo details.

  • Editing particular ToDo List data: Click on any particular item Edit button to Open the edit ToDo List item.

  • Deleting particular Todo List data: Click  on any particular item Delete button to delete the ToDo List item

Note: Please note, scaffolding gives us only basic functions and we cannot rely solely on it. It helps to ignite the basic setup and we can enhance further to get full-featured functionality.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!