We will also use some ADO.NET code to connect to our database to do the CRUD operations. All we will do here is use a Business Layer containing our logic. Also, Bootstrapping is implemented in this example.

Download the source code here.

Step 1

Create an empty ASP.NET web application with MVC.

console application

Empty website

Step 2

Add a Class Library project for the business layer to the solution.

add new project

class liberary

Step 3

Add two class files to this Class Library Project. One class will be used to declare entities and the other is used to implement the logic.

add new class

add class

class

Step 4

Open SQL Server Management Studio and run this script.

  1. CREATE TABLE [dbo].[Employee] (
  2. [EmployeeID] INT IDENTITY (1, 1) NOT NULL,
  3. [EmployeeName] NVARCHAR (50) NULL,
  4. [EmployeeGender] NVARCHAR (10) NULL,
  5. [EmployeeDesignation] NVARCHAR (50) NULL,
  6. PRIMARY KEY CLUSTERED ([EmployeeID] ASC)
  7. );
  8. INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [EmployeeGender], [EmployeeDesignation]) VALUES (1, N'Anna', N'Female', N'Software Engineer')
  9. INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [EmployeeGender], [EmployeeDesignation]) VALUES (2, N'Barace', N'Male', N'Software Engineer')
  10. INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [EmployeeGender], [EmployeeDesignation]) VALUES (3, N'Cathy', N'Female', N'Software Engineer')
  11. INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [EmployeeGender], [EmployeeDesignation]) VALUES (4, N'Downey', N'Male', N'Senior Software Engineer')
  12. INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [EmployeeGender], [EmployeeDesignation]) VALUES (5, N'Eric', N'Male', N'Senior Software Engineer')
  13. INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [EmployeeGender], [EmployeeDesignation]) VALUES (6, N'Foster', N'Male', N'Senior Software Engineer')
  14. INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [EmployeeGender], [EmployeeDesignation]) VALUES (7, N'Genee', N'Female', N'Senior Software Engineer')
  15. INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [EmployeeGender], [EmployeeDesignation]) VALUES (8, N'Howard', N'Male', N'Senior Software Engineer')
  16. INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [EmployeeGender], [EmployeeDesignation]) VALUES (9, N'Instana', N'Female', N'Project Manager')
  17. INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [EmployeeGender], [EmployeeDesignation]) VALUES (10, N'Joe', N'Male', N'Project Manager')
  18. INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [EmployeeGender], [EmployeeDesignation]) VALUES (11, N'Kristen', N'Male', N'Senior Manager')
  19. Select * from Employee
  20. CREATE PROCEDURE spGetAllEmployees
  21. AS
  22. BEGIN
  23. SELECT emp.*
  24. FROM dbo.Employee emp;
  25. END;
  26. CREATE PROCEDURE spInsertEmployeeDetails
  27. @EmployeeName NVARCHAR(50),
  28. @EmployeeGender NVARCHAR(10),
  29. @EmployeeDesignation NVARCHAR(50)
  30. AS
  31. BEGIN
  32. INSERT dbo.Employee
  33. (
  34. --EmployeeID - this column value is auto-generated
  35. EmployeeName,
  36. EmployeeGender,
  37. EmployeeDesignation
  38. )
  39. VALUES
  40. (
  41. -- EmployeeID - int
  42. N'', -- EmployeeName - nvarchar
  43. N'', -- EmployeeGender - nvarchar
  44. N'' -- EmployeeDesignation - nvarchar
  45. )
  46. END;
  47. CREATE PROCEDURE spUpdateEmployee
  48. @EmployeeID int,
  49. @EmployeeName nvarchar(100),
  50. @EmployeeGender nvarchar(10),
  51. @EmployeeDesignation nvarchar(100)
  52. AS
  53. BEGIN
  54. UPDATE dbo.Employee
  55. SET
  56. --EmployeeID - this column value is auto-generated
  57. dbo.Employee.EmployeeName = @EmployeeName, -- nvarchar
  58. dbo.Employee.EmployeeGender = @EmployeeGender, -- nvarchar
  59. dbo.Employee.EmployeeDesignation = @EmployeeDesignation-- nvarchar
  60. WHERE
  61. dbo.Employee.EmployeeID = @EmployeeID
  62. END
  63. CREATE PROCEDURE spDeleteEmployee
  64. @EmployeeID INT
  65. AS
  66. BEGIN
  67. DELETE dbo.Employee
  68. WHERE dbo.Employee.EmployeeID = @EmployeeID;
  69. END;
Explanation:

Step 5

Add the following code to the Employee class file we created in Step 3.

  1. using System.ComponentModel.DataAnnotations;
  2. namespace BusinessLayer
  3. {
  4. public class Employee
  5. {
  6. public int EmployeeID { get; set; }
  7. [Required]
  8. public string EmployeeName { get; set; }
  9. [Required]
  10. public string EmployeeGender { get; set; }
  11. [Required]
  12. public string EmployeeDesignation { get; set; }
  13. }
  14. }
We have just declared the properties corresponding to columns in the database table. All these properties are auto implemented and are wrapped inside the Employee class. We will use this employee class everywhere in the project.

Step 6

Add the following code to the Employee Business Layer Class that was also created in Step 3.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Data.SqlClient;
  6. namespace BusinessLayer
  7. {
  8. public class EmployeeBusinessLayer
  9. {
  10. public IEnumerable<Employee> Employees
  11. {
  12. get
  13. {
  14. string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
  15. List<Employee> employees = new List<Employee>();
  16. using (SqlConnection con = new SqlConnection(CS))
  17. {
  18. con.Open();
  19. SqlCommand cmd = new SqlCommand("spGetAllEmployees", con);
  20. cmd.CommandType = CommandType.StoredProcedure;
  21. SqlDataReader dr = cmd.ExecuteReader();
  22. while (dr.Read())
  23. {
  24. Employee employee = new Employee();
  25. employee.EmployeeID = Convert.ToInt32(dr["EmployeeID"]);
  26. employee.EmployeeName = dr["EmployeeName"].ToString();
  27. employee.EmployeeGender = dr["EmployeeGender"].ToString();
  28. employee.EmployeeDesignation = dr["EmployeeDesignation"].ToString();
  29. employees.Add(employee);
  30. }
  31. }
  32. return employees;
  33. }
  34. }
  35. public void AddEmployee(Employee employee)
  36. {
  37. string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
  38. using (SqlConnection con = new SqlConnection(CS))
  39. {
  40. con.Open();
  41. SqlCommand cmd = new SqlCommand("spInsertEmployeeDetails", con);
  42. cmd.CommandType = CommandType.StoredProcedure;
  43. cmd.Parameters.AddWithValue("@EmployeeName", employee.EmployeeName);
  44. cmd.Parameters.AddWithValue("@EmployeeGender", employee.EmployeeGender);
  45. cmd.Parameters.AddWithValue("@EmployeeDesignation", employee.EmployeeDesignation);
  46. cmd.ExecuteNonQuery();
  47. }
  48. }
  49. public void UpdateEmployee(Employee employee)
  50. {
  51. string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
  52. using (SqlConnection con = new SqlConnection(CS))
  53. {
  54. con.Open();
  55. SqlCommand cmd = new SqlCommand("spUpdateEmployee", con);
  56. cmd.CommandType = CommandType.StoredProcedure;
  57. cmd.Parameters.AddWithValue("@EmployeeID", employee.EmployeeID);
  58. cmd.Parameters.AddWithValue("@EmployeeName", employee.EmployeeName);
  59. cmd.Parameters.AddWithValue("@EmployeeGender", employee.EmployeeGender);
  60. cmd.Parameters.AddWithValue("@EmployeeDesignation", employee.EmployeeDesignation);
  61. cmd.ExecuteNonQuery();
  62. }
  63. }
  64. public void DeleteEmployee(int id)
  65. {
  66. string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
  67. using (SqlConnection con = new SqlConnection(CS))
  68. {
  69. con.Open();
  70. SqlCommand cmd = new SqlCommand("spDeleteEmployee", con);
  71. cmd.CommandType = CommandType.StoredProcedure;
  72. cmd.Parameters.AddWithValue("@EmployeeID", id);
  73. cmd.ExecuteNonQuery();
  74. }
  75. }
  76. }
  77. }
Explanation:

So, until now we have created the model of our application. Now the Controller and Views are left. Let's implement them also.

Step 7

Build the solution by pressing Ctrl + Shift + B. Now add a reference for the Business Layer into your MVC Project.

add reference

Solution

Step 8

Add a controller class to the controller folder.

add controller

MVC

controller name

Step 9

Add the following code to this file.

  1. using BusinessLayer;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web.Mvc;
  5. namespace MVCDataAccessByLayers.Controllers
  6. {
  7. public class EmployeeController : Controller
  8. {
  9. public ActionResult Index()
  10. {
  11. EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
  12. List<Employee> employees = employeeBusinessLayer.Employees.ToList();
  13. return View(employees);
  14. }
  15. [HttpGet]
  16. public ActionResult Create()
  17. {
  18. return View();
  19. }
  20. [HttpPost]
  21. public ActionResult Create(Employee employee)
  22. {
  23. if (ModelState.IsValid)
  24. {
  25. EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
  26. employeeBusinessLayer.AddEmployee(employee);
  27. return RedirectToAction("Index", "Employee");
  28. }
  29. return View();
  30. }
  31. [HttpGet]
  32. public ActionResult Edit(int id)
  33. {
  34. EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
  35. Employee employee = employeeBusinessLayer.Employees.Single(emp => emp.EmployeeID == id);
  36. return View(employee);
  37. }
  38. [HttpPost]
  39. public ActionResult Edit(Employee employee)
  40. {
  41. if (ModelState.IsValid)
  42. {
  43. EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
  44. employeeBusinessLayer.UpdateEmployee(employee);
  45. return RedirectToAction("Index", "Employee");
  46. }
  47. return View();
  48. }
  49. [HttpGet]
  50. public ActionResult Delete(int id)
  51. {
  52. EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
  53. employeeBusinessLayer.DeleteEmployee(id);
  54. return RedirectToAction("Index", "Employee");
  55. }
  56. public ActionResult Details(int id)
  57. {
  58. EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
  59. Employee employee = employeeBusinessLayer.Employees.Single(emp => emp.EmployeeID == id);
  60. return View(employee);
  61. }
  62. }
  63. }
Explanation:

In you have any query regarding this then please comment, I will reply to that at the earliest.

Step 10

Create Views for all of the Action Methods except the Delete Action Method.

click add view

Model class

Add view

Click ADD

type view name

Step 11

Replace with the following code for View files created in the preceding step.

Index.cshtml

  1. @model IEnumerable<BusinessLayer.Employee>
  2. @{
  3. ViewBag.Title = "Index";
  4. }
  5. <div class="container">
  6. <div class="jumbotron text-center"><h1>Employee Details</h1></div>
  7. <p>
  8. @Html.ActionLink("Create New", "Create")
  9. </p>
  10. <table class="table">
  11. <tr>
  12. <th>
  13. Name
  14. </th>
  15. <th>
  16. Gender
  17. </th>
  18. <th>
  19. Designation
  20. </th>
  21. <th></th>
  22. </tr>
  23. @foreach (var item in Model)
  24. {
  25. <tr>
  26. <td>
  27. @Html.DisplayFor(modelItem => item.EmployeeName)
  28. </td>
  29. <td>
  30. @Html.DisplayFor(modelItem => item.EmployeeGender)
  31. </td>
  32. <td>
  33. @Html.DisplayFor(modelItem => item.EmployeeDesignation)
  34. </td>
  35. <td>
  36. @Html.ActionLink("Edit", "Edit", new { id = item.EmployeeID }) |
  37. @Html.ActionLink("Details", "Details", new { id = item.EmployeeID }) |
  38. @Html.ActionLink("Delete", "Delete", new { id = item.EmployeeID })
  39. </td>
  40. </tr>
  41. }
  42. </table>
  43. </div>
Create.cshtml
  1. @model BusinessLayer.Employee
  2. @{
  3. ViewBag.Title = "Create";
  4. }
  5. <h2>Create</h2>
  6. @using (Html.BeginForm())
  7. {
  8. @Html.AntiForgeryToken()
  9. <div class="form-horizontal">
  10. <h4>Employee</h4>
  11. <hr />
  12. @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  13. <div class="form-group">
  14. @Html.LabelFor(model => model.EmployeeName, htmlAttributes: new { @class = "control-label col-md-2" })
  15. <div class="col-md-10">
  16. @Html.EditorFor(model => model.EmployeeName, new { htmlAttributes = new { @class = "form-control" } })
  17. @Html.ValidationMessageFor(model => model.EmployeeName, "", new { @class = "text-danger" })
  18. </div>
  19. </div>
  20. <div class="form-group">
  21. @Html.LabelFor(model => model.EmployeeGender, htmlAttributes: new { @class = "control-label col-md-2" })
  22. <div class="col-md-10">
  23. @Html.EditorFor(model => model.EmployeeGender, new { htmlAttributes = new { @class = "form-control" } })
  24. @Html.ValidationMessageFor(model => model.EmployeeGender, "", new { @class = "text-danger" })
  25. </div>
  26. </div>
  27. <div class="form-group">
  28. @Html.LabelFor(model => model.EmployeeDesignation, htmlAttributes: new { @class = "control-label col-md-2" })
  29. <div class="col-md-10">
  30. @Html.EditorFor(model => model.EmployeeDesignation, new { htmlAttributes = new { @class = "form-control" } })
  31. @Html.ValidationMessageFor(model => model.EmployeeDesignation, "", new { @class = "text-danger" })
  32. </div>
  33. </div>
  34. <div class="form-group">
  35. <div class="col-md-offset-2 col-md-10">
  36. <input type="submit" value="Create" class="btn btn-default" />
  37. </div>
  38. </div>
  39. </div>
  40. }
  41. <div>
  42. @Html.ActionLink("Back to List", "Index")
  43. </div>
  44. <script src="~/Scripts/jquery-1.10.2.min.js"></script>
  45. <script src="~/Scripts/jquery.validate.min.js"></script>
  46. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Edit.cshtml
  1. @model BusinessLayer.Employee
  2. @{
  3. ViewBag.Title = "Edit";
  4. }
  5. <h2>Edit</h2>
  6. @using (Html.BeginForm())
  7. {
  8. @Html.AntiForgeryToken()
  9. <div class="form-horizontal">
  10. <h4>Employee</h4>
  11. <hr />
  12. @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  13. @Html.HiddenFor(model => model.EmployeeID)
  14. <div class="form-group">
  15. @Html.LabelFor(model => model.EmployeeName, htmlAttributes: new { @class = "control-label col-md-2" })
  16. <div class="col-md-10">
  17. @Html.EditorFor(model => model.EmployeeName, new { htmlAttributes = new { @class = "form-control" } })
  18. @Html.ValidationMessageFor(model => model.EmployeeName, "", new { @class = "text-danger" })
  19. </div>
  20. </div>
  21. <div class="form-group">
  22. @Html.LabelFor(model => model.EmployeeGender, htmlAttributes: new { @class = "control-label col-md-2" })
  23. <div class="col-md-10">
  24. @Html.EditorFor(model => model.EmployeeGender, new { htmlAttributes = new { @class = "form-control" } })
  25. @Html.ValidationMessageFor(model => model.EmployeeGender, "", new { @class = "text-danger" })
  26. </div>
  27. </div>
  28. <div class="form-group">
  29. @Html.LabelFor(model => model.EmployeeDesignation, htmlAttributes: new { @class = "control-label col-md-2" })
  30. <div class="col-md-10">
  31. @Html.EditorFor(model => model.EmployeeDesignation, new { htmlAttributes = new { @class = "form-control" } })
  32. @Html.ValidationMessageFor(model => model.EmployeeDesignation, "", new { @class = "text-danger" })
  33. </div>
  34. </div>
  35. <div class="form-group">
  36. <div class="col-md-offset-2 col-md-10">
  37. <input type="submit" value="Save" class="btn btn-default" />
  38. </div>
  39. </div>
  40. </div>
  41. }
  42. <div>
  43. @Html.ActionLink("Back to List", "Index")
  44. </div>
  45. <script src="~/Scripts/jquery-1.10.2.min.js"></script>
  46. <script src="~/Scripts/jquery.validate.min.js"></script>
  47. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Details.cshtml
  1. @model BusinessLayer.Employee
  2. @{
  3. ViewBag.Title = "Details";
  4. }
  5. <h2>Details</h2>
  6. <div>
  7. <h4>Employee</h4>
  8. <hr />
  9. <dl class="dl-horizontal">
  10. <dt>
  11. @Html.DisplayNameFor(model => model.EmployeeName)
  12. </dt>
  13. <dd>
  14. @Html.DisplayFor(model => model.EmployeeName)
  15. </dd>
  16. <dt>
  17. @Html.DisplayNameFor(model => model.EmployeeGender)
  18. </dt>
  19. <dd>
  20. @Html.DisplayFor(model => model.EmployeeGender)
  21. </dd>
  22. <dt>
  23. @Html.DisplayNameFor(model => model.EmployeeDesignation)
  24. </dt>
  25. <dd>
  26. @Html.DisplayFor(model => model.EmployeeDesignation)
  27. </dd>
  28. </dl>
  29. </div>
  30. <p>
  31. @Html.ActionLink("Edit", "Edit", new { id = Model.EmployeeID }) |
  32. @Html.ActionLink("Back to List", "Index")
  33. </p>
Note: The code for the preceding views will be generated automatically. You don't need to do anything. I have made some alteration to the design, in other words why I want you to replace the auto-generated code with the preceding code. The code that is generated automatically above is called Scaffolding.

Step 12

Replace the code of the Layout.cshtml page in the view folder. It is the Master Page for the project.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>@ViewBag.Title - E.M.S</title>
  7. <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
  8. <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
  9. <script src="~/Scripts/modernizr-2.6.2.js"></script>
  10. </head>
  11. <body>
  12. <div class="navbar navbar-inverse navbar-fixed-top">
  13. <div class="container">
  14. <div class="navbar-header">
  15. <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
  16. <span class="icon-bar"></span>
  17. <span class="icon-bar"></span>
  18. <span class="icon-bar"></span>
  19. </button>
  20. @Html.ActionLink("Employee Management System", "Index", "Employee", new { area = "" }, new { @class = "navbar-brand" })
  21. </div>
  22. <div class="navbar-collapse collapse">
  23. <ul class="nav navbar-nav">
  24. </ul>
  25. </div>
  26. </div>
  27. </div>
  28. <div class="container body-content">
  29. @RenderBody()
  30. <hr />
  31. <footer>
  32. <p>© @DateTime.Now.Year - My ASP.NET Demo Application</p>
  33. </footer>
  34. </div>
  35. <script src="~/Scripts/jquery-1.10.2.min.js"></script>
  36. <script src="~/Scripts/bootstrap.min.js"></script>
  37. </body>
  38. </html>
The preceding is the code of the Master Page for the project. It is completely bootstrapped.

Step 13

Add a connection string to the web.config file as in the following:
  1. <connectionStrings>
  2. <add connectionString="Data Source=ANKITBANSALPC;Initial Catalog=MVC;Integrated Security=True" name="DBCS" providerName="System.Data.SqlClient"/>
  3. </connectionStrings>
It will establish a connection to the database.

Step 14

Replace the code of the Route.config file with the following code.
  1. using System.Web.Mvc;
  2. using System.Web.Routing;
  3. namespace MVCDataAccessByLayers
  4. {
  5. public class RouteConfig
  6. {
  7. public static void RegisterRoutes(RouteCollection routes)
  8. {
  9. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  10. routes.MapRoute(
  11. name: "Default",
  12. url: "{controller}/{action}/{id}",
  13. defaults: new { controller = "Employee", action = "Index", id = UrlParameter.Optional }
  14. );
  15. }
  16. }
  17. }
The name of the controller is changed to Employee. No other change is being done to it. It will direct the user to the index action method of the Employee controller.

Step 15

Press F5 to run the project and you will see the screen like the following screenshots.

see page

create detail

edit detail

see employee detail

delete

Detail image

Edit

Employee detail

I hope you liked this demo. Please provide your precious comments that encourages me to create more demos.

Please read this article on my personal blog and website.