CodeDigest.Com Logo
Featured:

Creating Dynamic Data Website Like CRUD Operations in Asp.Net MVC Using Scaffolding

Tagged as: Asp.Net MVC Posted By

Dynamic Data Website released with Asp.Net 3.5 WebForms helped us to quickly create a website for performing CRUD operation on the database tables. Similar to that, for Asp.Net MVC and Asp.Net WebApi, Microsoft released a Scaffolding framework with Visual Studio (from 2013) for quickly creating CRUD (Create, Read, Update and Delete) operations for the database tables using Entity Framework. This scaffolding framework uses the T4 templates for automatic code generation with the help of Visual Studio IDE. Moving forward, let’s see how to use Scaffolding framework in Asp.Net MVC application to generate CRUD operations for our data model quickly.

For demonstration, let’s create a new Asp.Net MVC 5.0 site in Visual Studio 2015. Include the latest Entity Framework Nuget package using the Nuget Package Manager tool. For easy, understanding let’s use a simple Employee-Department model for understanding Asp.Net MVC Scaffolding. The data model below.

The DbContext class below.

public class DBModel : DbContext
{
    public DBModel()
        : base("name=DBModel")
    {
    }
    public DbSet<Department> Departments { get; set; }
    public DbSet<Employee> Employees { get; set; }

}
 

Now, let’s use the Scaffolding framework to create CRUD views and Controller action methods for Employee model. To do this, right click the Controllers folder, Click Add > New Scaffolded Item.. as seen in the below figure.

 

In the Add Scaffold dialogue as seen in below image, select “MVC 5 Controller with view, using Entity Framework”. Click Add.  

The above action will bring the “Add Controller” dialog as seen in below image. Select Model class dropdown to Employee model and select Data context class as DBModel. You can leave the rest of the settings as default or change it as per your need. Click Add.

This will create a new EmployeesController with CRUD action methods and it will also create views for the action method as seen below.

The EmployeesController code generated by the Scaffolding framework is below.

 

public class EmployeesController : Controller
{
    private DBModel db = new DBModel();

    // GET: Employees
    public ActionResult Index()
    {
        var employees = db.Employees.Include(e => e.Department);
        return View(employees.ToList());
    }

    // GET: Employees/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return HttpNotFound();
        }
        return View(employee);
    }

    // GET: Employees/Create
    public ActionResult Create()
    {
        ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentName");
        return View();
    }

    // POST: Employees/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "EmployeeId,DepartmentId,FirstName,LastName,Address1,Address2,City,State,Country,PostalCode, Email,ConfirmEmail,DOB,Gender,IsPermanent,Salary")] Employee employee)
    {
        if (ModelState.IsValid)
        {
            db.Employees.Add(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentName", employee.DepartmentId);
        return View(employee);
    }

    // GET: Employees/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return HttpNotFound();
        }
        ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentName", employee.DepartmentId);
        return View(employee);
    }

    // POST: Employees/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "EmployeeId,DepartmentId,FirstName,LastName,Address1,Address2,City,State,Country,PostalCode, Email,ConfirmEmail,DOB,Gender,IsPermanent,Salary")] Employee employee)
    {
        if (ModelState.IsValid)
        {
            db.Entry(employee).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentName", employee.DepartmentId);
        return View(employee);
    }

    // GET: Employees/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return HttpNotFound();
        }
        return View(employee);
    }

    // POST: Employees/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)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}
 

Please note that the CRUD operations support model validations configured using Data Annotations attributes and it can be further customized. You can also customize the views and the input fields further like any other MVC applications. The scaffolding framework just helps us to quickly generate a CRUD operations for the database tables with a default interface which can be further customized to our needs.

That’s it! When executed, you can see the list, delete, create and edit screens as seen below. You can also download the source attached at the end of this article and see it in action.

List Screen with Edit/Delete/Details Link

Create Screen

Edit Screen

Details Screen



Feedback

Comments