Scaffolding in ASP.NET MVC

WEBINAR: On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

Introduction

Scaffolding involves creating base templates for code or markup of project items through an automated method. The basic templates thus generated can then be customized to meet your exact requirements. The MvcScaffolding available as a NuGet package helps you scaffold ASP.NET MVC 3 specific project items such as Controllers and Views. The coding language for the resultant classes can be C# or VB. Similarly, views can be Razor based or ASPX based. In this article you will learn the basics of using MvcScaffolding package to generate CRUD interface for a database table.

Installing MvcScaffolding NuGet Package

MvcScaffolding is available as a NuGet package. Before you use any of the features of MvcScaffolding you must install the MvcScaffolding NuGet package in your project. Let's see how.

Begin by creating a new ASP.NET MVC 3 Web Application and name the project MvcScaffoldingDemo. While creating the project make sure to select ASPX as the view engine. Once the project is ready you can install the MvcScaffolding NuGet package. To do so, go to View > Other Windows > Package Manager Console and open Package Manager Console as shown below:

Open the Package Manager Console
Figure 1: Open the Package Manager Console

Now issue the following command to download and install the MvcScaffolding package.

Install-Package MvcScaffolding

The installation process will download all of the dependencies (Entity Framework 4.1 for example) as seen below:

The installation process will download all of the dependencies
Figure 2: The installation process will download all of the dependencies

Now that you have installed the MvcScaffolding package you are ready to scaffold controllers and views.

Creating the Database

It is not necessary to have a database to scaffold controllers and views; you will still add it for the sake of completeness and clarity. Add a new SQL Server database to the App_Data folder and create an Employee table in it. The schema of the Employee table is given below:

The schema of the Employee table
Figure 3: The schema of the Employee table

The Employee table is a simple table with four columns viz. Id, FirstName, LastName and BirthDate. Id is an identity column that acts as a primary key.

Next, you need to create a data model that matches the schema of Employee table. To do so, add a new class in Models folder and name it as Employee. The Employee class has public properties corresponding to the column names and is shown below:

namespace MvcScaffoldingDemo.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime BirthDate { get; set; }
    }
}

Scaffolding for CRUD Operations

Now that you have the model class ready, you can scaffold controller and views to perform CRUD (Create, Read, Update, Delete) operations. All you need to do is inform the MvsScaffolding package about the data model and it can generate the required controller action methods and views for you.

Open the Package Manager Console again and issue the following command:

Scaffold Controller Employee

The above scaffold command creates the following items based on the Employee model class:

  • A Controller class in the Controllers folder with the name EmployeesController
  • An Entity Framework Code First driven DbContext class - MvcScaffoldingDemoContext
  • ASPX Views for add, update and delete operations

The following figure shows all of the above items in the Solution Explorer.

Solution Explorer
Figure 4: Solution Explorer

If you open the EmployeesController class you will see the various action methods for adding, updating and deleting employees.

The EmployeesController class
Figure 5: The EmployeesController class

You can, of course, modify this code to meet your specific requirements.

Using the Generated Code

Now let's use the generated action methods and views to add some data in the Employees table. Recollect that you have already designed a database table in an SQL Express database. Though Code First development allows for auto-creation of the database, in our case we wish to use the existing database for further operations. Add <connectionStrings> section in the web.config file as shown below:

<connectionStrings>
  <add
    name="MvcScaffoldingDemoContext"
    providerName="System.Data.SqlClient"
    connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Bipin\MvcScaffoldingDemo\App_Data\Database1.mdf;
    Integrated Security=True;User Instance=True"/>
</connectionStrings>

Make sure to change the database connection string as per the setup at your end. Notice that the name of the connection string (MvcScaffoldingDemoContext) is the same as the DbContext class generated during the scaffolding process.

namespace MvcScaffoldingDemo.Models
{
    public class MvcScaffoldingDemoContext : DbContext
    {
       ...
    }
}

This is required so that at runtime the Entity Framework will pick the correct connection string from the web.config file.

NOTE:
If you don't specify the connection string in the web.config file, a new database will be created with the name same as the fully qualified name of data context class i.e. MvcScaffoldingDemo.Models.MvcScaffoldingDemoContext in our case.

Now, run the application and add a few Employee records. Also, try Edit, Details and Delete operations. The following figure shows an employee record in Edit mode:

An employee record in Edit mode
Figure 6: An employee record in Edit mode

Scaffolding Specific Items

In the preceding example you created all of the necessary project items required for a CRUD operation. You can also selectively generate them as per your requirement. For example, you can scaffold only views or only data context class. Consider the following examples that do these tasks respectively.

Scaffold Views -ModelType Employee -Force
Scaffold DbContext Employee MyDbContext

The first command creates all of the views required for CRUD operations. The -Force switch overwrites the existing view files if any. The second command creates a DbContext class named MyDbContext and adds a DbSet to it based on the model type (Employee).

The complete list of switches and other configuration options can be obtained at ASP.NET MVC Scaffolding.

Summary

MvcScaffolding is a powerful technique for quickly creating basic code and markup templates for ASP.NET MVC applications. You can then modify the code and markup to suit your needs. MvcScaffolding is available as a NuGet package that you need to install in your MVC project. This article demonstrated how a basic CRUD interface can be generated using the MvcScaffolding package. In addition to this basic use you can use the advanced features of MvcScaffolding package to highly customize the final output.



About the Author

Bipin Joshi

Bipin Joshi is a blogger and writes about apparently unrelated topics - Yoga & technology! A former Software Consultant by profession, Bipin has been programming since 1995 and has been working with the .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. He was a well known technology author, trainer and an active member of Microsoft developer community before he decided to take a backseat from the mainstream IT circle and dedicate himself completely to spiritual path. Having embraced Yoga way of life he now codes for fun and writes on his blogs. He can also be reached there.

Related Articles

Downloads

Comments

  • Pictures missing

    Posted by Rubem Nascimento da Rocha on 02/28/2013 01:26am

    The article's pictures are missing. I can't view them.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date