Scaffolding in ASP.NET MVC

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

  • cheap snapbacks for sale

    Posted by iwexpenueMoxjef on 03/29/2013 11:18pm

    [url=http://www.bestwholesalehats.com]snapback hats wholesale[/url]cheap sunglasses [url=http://www.bestwholesalehats.com]snapback hats wholesale[/url]wholesale snapbacks [url=http://www.bestcheapsnapbacks.com]cheap snapbacks free shipping[/url]cheap oakley [url=http://www.bestcheapsnapbacks.com]cheap snapbacks from china[/url]cheap snapbacks free shipping [url=http://www.bestcheapsnapbacks.com]cheap snapbacks free shipping[/url]cheap snapbacks

    Reply
  • Candy Lace lingerie

    Posted by Fishnetyo1012 on 03/29/2013 08:44am

    http://womenssexyclothes.webs.com - Lingerie CostumesIn this way, October 31st is not only a gateway to the realm of ghosts, ghouls, and goblins, but it's also a gateway to the realm of increased sex appeal and sexual confidences sex appeal http://cheapspicylingerie.webs.com - Cheap Bustiers?Similar to a corset in design, a teddy is a one piece suit that starts out as a bustier, extends down between the legs as a thong, and ends up fastening to the back of the bodice Babydolls have a brief but interesting history, of which many fans are unaware http://sexystockings.webs.com - sexy stockingsThe wholesale lingerie may include several items that include garter belts, brassiere, camisoles, gowns, panties, and so on We also know that people can get seriously depressed and stressed during this two-month season http://Lingeriesv.webs.com - white Lingerie  They will be able to give you a clearer idea of what styles of lingerie she likes to wear so you don’t make any mistakes, but also they will know which companies she prefers This means a woman can enhance the lower part of the body by a loose garment with a tight fit across the waist and the bosom, to bring a combination of a slim top and an emphasized nether region http://sexylingeriecostumes.webs.com - Intimate ApparelLet’s look a bit deeper into the colors Perhaps an afternoon can be allotted to the group to design, shop and decorate

    Reply
  • sexy lingerie for women

    Posted by Fishnetox1034 on 03/29/2013 07:45am

    http://cheapspicylingerie.webs.com - cheap sexy lingerie4 Babydoll chemises are also impressive lingerie that offer innocence and raw sensuality to a woman http://discounteroticlingerie.webs.com - Erotic LingerieMy Florida friend tunes in to his different operations at different times every day, and takes a few notes on what he sees Check for valid codes to get extra discounts http://sexycostumesus.webs.com - Sexy CostumesThis means a woman can enhance the lower part of the body by a loose garment with a tight fit across the waist and the bosom, to bring a combination of a slim top and an emphasized nether region It is the web http://spicylingeries.webs.com - Sheer Lingeriewhy don't you just ask her her size! When shopping for lingerie, keep in mind that a gift of lingerie should stimulate both you and your partnerThe wholesale lingerie is nothing different from any regular lingerie http://spicylingeries.webs.com - sexy lingerie for womenGot a nice set of abs? Look for an outfit that reveals your mid drift The next thing that you have to consider is the design

    Reply
  • fitted hats wholesale

    Posted by xxds9wx on 03/29/2013 12:02am

    [url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping n iylf [url=http://cheapsnapbackshat.webs.com]cheap hats for sale[/url] cheap hats for sale a pxgd[url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale s fyub[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping z wdfl[url=http://wholesalefittedhat.webs.com]snapbacks wholesale[/url] snapbacks wholesale x xcko[url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap e gxwa [url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks online[/url] cheap snapbacks online q ptql [url=http://goodsnapbackhatscheap.webs.com]cheap snapback hats[/url] cheap snapback hats m dmib[url=http://goodsnapbackhatscheap.webs.com]snapback hats cheap[/url] snapback hats cheap i uwfh[url=http://bestbaseballcap.webs.com]wholesale hats[/url] wholesale hats c eyzk[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping m mqdi[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks[/url] cheap snapbacks b uckd [url=http://snapbackhatwholesale.webs.com]wholesale beanies[/url] wholesale beanies i vsst [url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping w jtgk[url=http://wholesalefittedhat.webs.com]wholesale fitted hats[/url] wholesale fitted hats h iycc[url=http://bestbaseballcap.webs.com]wholesale snapback caps[/url] wholesale snapback caps n bnav[url=http://snapbackhatwholesale.webs.com]wholesale beanies[/url] wholesale beanies n kcao[url=http://cheaphatsmall.webs.com]cheap snapbacks[/url] cheap snapbacks h spod

    Reply
  • discount ray ban

    Posted by lgliliImpumpcyy on 03/28/2013 10:50pm

    discount oakleys [url=http://discountsunglassesfinewebs.com]discount oakleys[/url] fake ray ban sunglasses sunglasses wholesale [url=http://olesalesunglassesgood.webs.com]sunglasses wholesale[/url] fake oakley sunglasses ray ban wayfarer cheap [url=http://sunglassdicountsaleu.webs.com]ray ban wayfarer cheap[/url] oakley sunglasses discount wholesale oakley sunglasses [url=http://wholesalesunglassescool.webs.com]wholesale oakley sunglasses[/url] cheap oakley wayfarer sunglasses cheap [url=http://onlineguciisunglass.webs.com]wayfarer sunglasses cheap[/url] ray ban sunglasses cheap sunglasses wholesale [url=http://olesalesunglassesgood.webs.com]sunglasses wholesale[/url] ray ban sunglasses cheap cheap ray ban [url=http://sunglasssaleulow.webs.com]cheap ray ban[/url] fake ray ban oakley sunglasses cheap [url=http://cheapsunglassesshop.webs.com]oakley sunglasses cheap[/url] cheap sunglasses

    Reply
  • wholesale oakley sunglasses

    Posted by lgliliImpumpzsc on 03/28/2013 10:48pm

    http://guccicheapsunglass.webs.com - cheap ray ban fake ray ban http://discountsunglasseshoo.webs.com - discount sunglasses fake ray ban sunglasses http://discountoakleysunglassesho.webs.com - oakley sunglasses discount oakley sunglasses cheap http://fakeGucciwayfarer.webs.com - fake ray ban wayfarer sunglasses wholesale http://fakeguccisunglasses.webs.com - fake oakley sunglasses replica oakley sunglasses

    Reply
  • 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
  • ugg boots cgcrkj http://www.cheapfashionshoesam.com/

    Posted by Suttonjaa on 01/15/2013 05:52am

    0cMus cheap ugg boots nOji Michael Kors outlet mJrp ugg boots 0vWmi Burberry outlet 4bFxc Cheap nfl jerseys 9oXjs coach,coach outlet,coach outlet online,coach factory outlet 2kYjl burberry outlet 7wZtm christian louboutin 9lHmx 3iYxx 4wRoq 1dOdp 9rSuv 1yHbk 2zVdn

    Reply
  • jdpywxdm cvrmyyeh qmxrp http://achatzdoudounemonclairsonline.webnode.fr/

    Posted by PambInabe on 11/17/2012 07:26am

    zznrg tcnkq http://frdoudounemonclermagasinn.blogspot.com/ jfoba ukfjqh Scaffolding in ASP.NET MVC zgdqoxm abercrombie paris zjxhzfw xbomm louboutin homme ngkkpcpf air jordan femme agstqzln polo ralph lauren pas cher bcucvdfa

    Reply
  • http://www.cheapzccochbagsonline.us lutxkw mwunbi

    Posted by boowiffRodial on 11/16/2012 11:50pm

    cbvikv edsklp モンクレール ダウンベスト モンクレール 店舗 モンクレール ポロシャツ aufbftmb ugg outlet minnesota ugg boots ugg boots best price jnjllhj fejrrla qksov Scaffolding in ASP.NET MVC xvjtmfw louis vuitton handbags vernis louis vuitton bags louis vuitton outlet philadelphia xopkyspf beats by dre headquarters cheap beats dre cheap beats by dre usa hpxrmvrd

    Reply
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • Hybrid cloud platforms need to think in terms of sweet spots when it comes to application platform interface (API) integration. Cloud Velocity has taken a unique approach to tight integration with the API sweet spot; enough to support the agility of physical and virtual apps, including multi-tier environments and databases, while reducing capital and operating costs. Read this case study to learn how a global-level Fortune 1000 company was able to deploy an entire 6+ TB Oracle eCommerce stack in Amazon Web …

  • Event Date: April 15, 2014 The ability to effectively set sales goals, assign quotas and territories, bring new people on board and quickly make adjustments to the sales force is often crucial to success--and to the field experience! But for sales operations leaders, managing the administrative processes, systems, data and various departments to get it all right can often be difficult, inefficient and manually intensive. Register for this webinar and learn how you can: Align sales goals, quotas and …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds