Scaffolding in ASP.NET MVC 4.0

Scaffolding is one of the nice feature in ASP.NET MVC. The main purpose of scaffolding is it creates a starting point of code for you. Whatever application you are developing, you need to create Controller, Action Methods, Views and probably a database connection. Without scaffolding you need to do almost similar kind of job every time. It actually save some of your time by creating the basic code structure for you, on which you can start your work. You can change the scaffolding code to meet your exact requirement. Keep in mind that scaffolding code is not the final application code. It is just a starting point from you need to continue. If you are not happy with the way scaffolding works. You can change it. You can configure it to create basic starting code structure of your choice.

By default ASP.NET scaffolding has some options from which you need to choose. Depending on your choice it creates Controller with basic CRUD action methods, Views for every Action Methods, Data Context class using Entity Framework code first approach. If you choose to create Entity Framework data context for you then it will also add a connection string in web.config file and create a data base depending your model class structure at the App_Data folder in your application. For scaffolding to work you need to create your model class structure first. Because Visual Studio has no clue about your domain and what type of problem you are going to solve, that’s why you need to create the model structure to scaffolding to work. From the model structure scaffolding get clue and create basic code structure for you to continue.

If you do not know about code first approach, then you need to search for that. To give you an basic idea, code first approach means when you first create your domain class and then from domain class your data base will generate. Another approach is data base first approach, where you design data base first and then create domain class for your application from database. In Entity Framework there is another approach named model first approach. In model first approach you first create your application domain structure in Entity Framework visual designer. The designer creates the classes and also creates a database script for you. You can then create the database from the generated database script. In this way depending on where you start the initial development your approach will be named.

To show you an example I am going to create a very basic application in Visual Studio 2012 with ASP.NET MVC 4.0. I will just write my model class and let Visual Studio to scaffold the code depending on model class. Also I need to persists my model data to data base so I will use Entity Framework code first approach. I will use SQL Server Express Edition.

I am creating a new internet application with ASP.NET MVC 4.0. After creation of the project files, I am creating a Employee class in Model folder.

namespace Scaffolding.Models
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }
}

After creating the model class, I need to create controller with basic action methods and views for them. Also I want to persistent my employee data in to SQL Server. I can manually write all the code or I can use the scaffolding in Visual Studio 2012. Here at the time of adding a new controller for employee I can tell Visual Studio to scaffold and create controller with basic CRUD functionality using Entity Framework code first approach and views for every action methods depending on my model class (Employee class). You can give all the options from giving a sweetable controller name, scaffolding option, your model class, your data context class and the view engine for your views. If you has an existing Entity Framework data context class, then you can use it in scaffolding or you if you do not, you can tell Visual Studio to create a new one for you. After giving all information I am clicking on Add button and Visual Studio scaffolding creates a basic structure to continue for me.

Scaffolding Options
Scaffolding Options
New Files After Scaffolding
New Files After Scaffolding
using System.Data;
using System.Linq;
using System.Web.Mvc;
using Scaffolding.Models;

namespace Scaffolding.Controllers
{
    public class EmployeeController : Controller
    {
        private EmployeeContext db = new EmployeeContext();

        //
        // GET: /Employee/

        public ActionResult Index()
        {
            return View(db.Employees.ToList());
        }

        //
        // GET: /Employee/Details/5

        public ActionResult Details(int id = 0)
        {
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        //
        // GET: /Employee/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Employee/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(employee);
        }

        //
        // GET: /Employee/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        //
        // POST: /Employee/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Entry(employee).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employee);
        }

        //
        // GET: /Employee/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        //
        // POST: /Employee/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Employee employee = db.Employees.Find(id);
            db.Employees.Remove(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
using System.Data.Entity;

namespace Scaffolding.Models
{
    public class EmployeeContext : DbContext
    {
        public EmployeeContext() : base("name=EmployeeContext")
        {
        }

        public DbSet<Employee> Employees { get; set; }
    }
}

You can see the new files created by Visual Studio in Solution Explorer. I post the controller and Entity Framework data context code for you to understand easily. Inside controller you can see that Entity Framework data context has been used to work with database. If I write attributes for validation in my model class properties then you can see input validation performing at the time of inserting and updating employee data from the browser. When I first run the application and go in to the employee URL the Entity Framework will automatically creates my database and place it in App_Data folder of this application. Now I can add, edit, delete and view employee data from the browser. All I need to write my model class.

Conclusion

Use scaffolding to save coding time. If you want a different type of scaffolding, you can configure it. You can use any framework other than Entity Framework in scaffolding. You are not bound with the generated code. You can change it. It is to help you.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s