0% found this document useful (0 votes)
52 views

CRUD With Dapper Documentation2

Uploaded by

heyaaru2000
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

CRUD With Dapper Documentation2

Uploaded by

heyaaru2000
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Sure!

Here’s a complete step-by-step guide for creating your MVC


application with CRUD operations, including the latest changes for
search functionality. This guide includes the project setup, database
configuration, repository, controller, and view changes, along with the
added pagination, search, and stored procedure.

Documentation for MVC CRUD Project with Search and Pagination

1. Project Setup

1. Open Visual Studio and create a new ASP.NET MVC Web


Application.

2. Choose MVC as the project type.

3. Install the following NuGet packages:

o Dapper (to interact with the database using Dapper ORM).

o Microsoft.Data.SqlClient (for SQL Server connection).

2. Database Setup

In SQL Server, create a new database called EmployeeDB. Then, create an


Employees table.

CREATE DATABASE EmployeeDB;

USE EmployeeDB;

CREATE TABLE Employees

Id INT PRIMARY KEY IDENTITY (1,1),

Name NVARCHAR(100),

Age INT,

Department NVARCHAR(50),

IsDeleted BIT Default 0

);
Stored Procedures

You will need several stored procedures for various operations like
fetching data, inserting, updating, soft-deleting, and searching employees.
Here are the stored procedures you should create.

2.1. Pagination Stored Procedure

CREATE PROCEDURE spGetEmployeesWithPagination

@PageNumber INT,

@PageSize INT

AS

BEGIN

SELECT *

FROM Employees

WHERE IsDeleted = 0

ORDER BY Id

OFFSET (@PageNumber - 1) * @PageSize ROWS FETCH NEXT @PageSize


ROWS ONLY;

END;

2.2. Insert Stored Procedure

CREATE PROCEDURE spInsertEmployee

@Name NVARCHAR(100),

@Age INT,

@Department NVARCHAR(50)

AS

BEGIN

INSERT INTO Employees (Name, Age, Department, IsDeleted)

VALUES (@Name, @Age, @Department, 0);

END;

2.3. Update Stored Procedure

CREATE PROCEDURE spUpdateEmployee

@Id INT,
@Name NVARCHAR(100),

@Age INT,

@Department NVARCHAR(50)

AS

BEGIN

UPDATE Employees

SET Name = @Name, Age = @Age, Department = @Department

WHERE Id = @Id;

END;

2.4. Soft Delete Stored Procedure

CREATE PROCEDURE spSoftDeleteEmployee

@Id INT

AS

BEGIN

UPDATE Employees

SET IsDeleted = 1

WHERE Id = @Id;

END;

2.5. Search Stored Procedure

CREATE PROCEDURE spSearchEmployees

@SearchTerm NVARCHAR(100)

AS

BEGIN

SELECT *

FROM Employees

WHERE (Name LIKE '%' + @SearchTerm + '%'

OR Department LIKE '%' + @SearchTerm + '%')

AND IsDeleted = 0;
END;

3. Model Setup

In your project, add a Models folder, and within it, create a file called
Employee.cs.

Employee.cs (Model)

using System;

namespace PracticeWeb.Models

public class Employee

public int Id { get; set; }

public string Name { get; set; }

public int Age { get; set; }

public string Department { get; set; }

public bool IsDeleted { get; set; }

4. Employee Repository
Create a folder called Repositories and add a file called
EmployeeRepository.cs. This file will contain all the methods for
interacting with the database using Dapper.

Updated EmployeeRepository.cs

using System;

using System.Collections.Generic;

using System.Data.SqlClient;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Configuration;

using Dapper;

namespace CRUD.Models

public class EmployeeRepository

private readonly string _connectionString =


WebConfigurationManager.ConnectionStrings["EmployeeDBConnection"].C
onnectionString;

public (List<Employee>, int) GetPaginatedEmployees(int


pageNumber, int pageSize, string searchTerm = null)

using (IDbConnection db = new SqlConnection(_connectionString))

var parameters = new DynamicParameters();

parameters.Add("@PageNumber", pageNumber);

parameters.Add("@PageSize", pageSize);

parameters.Add("@SearchTerm", searchTerm);
using (var multi = db.QueryMultiple("GetPaginatedEmployees",
parameters, commandType: CommandType.StoredProcedure))

var employees = multi.Read<Employee>().ToList();

var totalRecords = multi.Read<int>().FirstOrDefault();

return (employees, totalRecords);

public Employee GetEmployeeById(int id)

using (IDbConnection db = new SqlConnection(_connectionString))

return
db.QuerySingleOrDefault<Employee>("spGetEmployeeById", new { Id =
id }, commandType: CommandType.StoredProcedure);

public void InsertEmployee(Employee employee)

using (IDbConnection db = new SqlConnection(_connectionString))

var parameters = new { Name = employee.Name, Age =


employee.Age, Department = employee.Department };

db.Execute("spInsertEmployee", parameters, commandType:


CommandType.StoredProcedure);

}
public void UpdateEmployee(Employee employee)

using (IDbConnection db = new SqlConnection(_connectionString))

var parameters = new { Id = employee.Id, Name =


employee.Name, Age = employee.Age, Department =
employee.Department };

db.Execute("spUpdateEmployee", parameters, commandType:


CommandType.StoredProcedure);

public void SoftDeleteEmployee(int id)

using (IDbConnection db = new SqlConnection(_connectionString))

db.Execute("spSoftDeleteEmployee", new { Id = id },
commandType: CommandType.StoredProcedure);

public IEnumerable<Employee> GetEmployees(int pageNumber, int


pageSize)

using (IDbConnection db = new SqlConnection(_connectionString))

return db.Query<Employee>("spGetEmployeesWithPagination",

new { PageNumber = pageNumber, PageSize = pageSize },

commandType: CommandType.StoredProcedure);

}
}

5. Controller Setup

Create a new controller called EmployeeController that will interact with


the repository.

Updated EmployeeController.cs

using CRUD.Models;
using Dapper;

using System;

using System.Collections.Generic;

using System.Data.SqlClient;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace CRUD.Controllers

public class EmployeeController : Controller

private EmployeeRepository _employeeRepository = new


EmployeeRepository();

public ActionResult Index(int page = 1, int pageSize = 5, string


searchTerm = "")

var (employees, totalRecords) =


_employeeRepository.GetPaginatedEmployees(page, pageSize,
searchTerm);

//ye employees ka object hai jo ki list hai aur totalRecords ka


object hai jo ki int hai

//ye dono object ek tuple mei store kiye gaye hai

//tuple mei ek se zyada values store kiye ja sakte hai

//tuple mei values ko access karne ke liye hum tuple ke variable ke


sath dot(.) laga kar access kar sakte hai

ViewBag.TotalRecords = totalRecords;
ViewBag.PageSize = pageSize;

ViewBag.CurrentPage = page;

ViewBag.SearchTerm = searchTerm;

return View(employees);

public ActionResult Create()

return View();

[HttpPost]

public ActionResult Create(Employee employee)

if (ModelState.IsValid)

_employeeRepository.InsertEmployee(employee);

return RedirectToAction("Index");//agar model state valid hua


toh index pe le jao

return View(employee); //agar model state valid nahi hua toh


wapas view pe le jao

//get wala hai ye

public ActionResult Edit(int id)

{
var employee = _employeeRepository.GetEmployeeById(id);

if (employee == null)

return HttpNotFound();

return View(employee);

[HttpPost]

public ActionResult Edit(Employee employee)

if (ModelState.IsValid)

_employeeRepository.UpdateEmployee(employee);

return RedirectToAction("Index");

return View(employee);

public ActionResult Delete(int id)

_employeeRepository.SoftDeleteEmployee(id);

return RedirectToAction("Index");

}
1. Adding Bootstrap to the Project

First, make sure you have Bootstrap 5 added to your project. You can do
this by adding the Bootstrap CDN to your layout page.

_Layout.cshtml (Located in the Views/Shared folder)

This is the shared layout for all views, and we will include Bootstrap here:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>@ViewBag.Title</title>

<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.
css" rel="stylesheet" />

<style>

/* Custom CSS for enhancing visual appeal */

body {

background-color: #f8f9fa;

font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;

.navbar {

background-color: #343a40;

}
.navbar a {

color: white !important;

h2 {

margin-top: 20px;

.table-hover tbody tr:hover {

background-color: #f1f1f1;

.btn-custom {

background-color: #17a2b8;

color: white;

.btn-custom:hover {

background-color: #138496;

color: white;

.form-control, .btn {

margin-top: 10px;

</style>

</head>

<body>

<nav class="navbar navbar-expand-lg navbar-dark">

<div class="container-fluid">

<a class="navbar-brand" href="#">Employee Management</a>

</div>

</nav>

<div class="container">
@RenderBody()

</div>

<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle
.min.js"></script>

</body>

</html>

2. Employee List View with Search and Pagination

Next, let's create the Index.cshtml file to list all employees, add a search
bar, and include pagination controls.

Index.cshtml (Located in the Views/Employee folder)

@model IEnumerable<CRUD.Models.Employee>

<h2 class="text-center mb-4">Employee List</h2>

<div class="row mb-4">

<div class="col-md-8">

<form action="@Url.Action("Index", "Employee")" method="get"


class="d-flex">

<input type="text" name="searchTerm" class="form-control me-


2" value="@ViewBag.SearchTerm" placeholder="Search employees..." />

<button type="submit" class="btn


btn-primary">Search</button>

</form>

</div>

<div class="col-md-4 text-end">

<a href="@Url.Action("Create", "Employee")" class="btn btn-


danger">Add New Employee</a>

</div>

</div>
<div class="table-responsive">

<table class="table table-bordered table-hover">

<thead class="table-primary">

<tr>

<th>Name</th>

<th>Age</th>

<th>Department</th>

<th>Actions</th>

</tr>

</thead>

<tbody>

@foreach (var employee in Model)

<tr>

<td>@employee.Name</td>

<td>@employee.Age</td>

<td>@employee.Department</td>

<td>

<a href="@Url.Action("Edit", "Employee", new { id =


employee.Id })" class="btn btn-primary btn-sm">Edit</a>

<a href="@Url.Action("Delete", "Employee", new { id =


employee.Id })" class="btn btn-danger btn-sm">Delete</a>

</td>

</tr>

</tbody>

</table>

</div>
<nav class="fixed-bottom mb-4">

<ul class="pagination justify-content-center">

@if (ViewBag.CurrentPage > 1)

<li class="page-item">

<a class="page-link" href="@Url.Action("Index", new { page =


ViewBag.CurrentPage - 1, pageSize = ViewBag.PageSize, searchTerm =
ViewBag.SearchTerm })">Previous</a>

</li>

@for (var i = 1; i <= Math.Ceiling((double)ViewBag.TotalRecords /


ViewBag.PageSize); i++)

<li class="page-item @(i == ViewBag.CurrentPage ? "active" :


"")">

<a class="page-link" href="@Url.Action("Index", new { page =


i, pageSize = ViewBag.PageSize, searchTerm =
ViewBag.SearchTerm })">@i</a>

</li>

@if (ViewBag.CurrentPage <


Math.Ceiling((double)ViewBag.TotalRecords / ViewBag.PageSize))

<li class="page-item">

<a class="page-link" href="@Url.Action("Index", new { page =


ViewBag.CurrentPage + 1, pageSize = ViewBag.PageSize, searchTerm =
ViewBag.SearchTerm })">Next</a>

</li>

}
</ul>

</nav>

3. Create New Employee Form

The Create.cshtml view will contain the form to add a new employee.
Bootstrap's form classes are used to style the form.

Create.cshtml

@{

ViewBag.Title = "Create";

@model CRUD.Models.Employee

<h2 class="text-center">Add New Employee</h2>

@using (Html.BeginForm())

<div class="mb-3">

@Html.LabelFor(m => m.Name, new { @class = "form-label" })

@Html.TextBoxFor(m => m.Name, new { @class = "form-control",


placeholder = "Enter employee name" })

@Html.ValidationMessageFor(m => m.Name, "", new { @class =


"text-danger" })

</div>

<div class="mb-3">

@Html.LabelFor(m => m.Age, new { @class = "form-label" })

@Html.TextBoxFor(m => m.Age, new { @class = "form-control",


placeholder = "Enter employee age" })

@Html.ValidationMessageFor(m => m.Age, "", new { @class = "text-


danger" })
</div>

<div class="mb-3">

@Html.LabelFor(m => m.Department, new { @class = "form-


label" })

@Html.TextBoxFor(m => m.Department, new { @class = "form-


control", placeholder = "Enter department" })

@Html.ValidationMessageFor(m => m.Department, "", new { @class


= "text-danger" })

</div>

<button type="submit" class="btn btn-success">Submit</button>

4. Edit Employee Form

This form will allow users to update existing employee details. The UI is
similar to the Create form, with Bootstrap styling.

Edit.cshtml

@{

ViewBag.Title = "Edit";

@model CRUD.Models.Employee

<h2 class="text-center">Edit Employee</h2>

@using (Html.BeginForm())

@Html.HiddenFor(m => m.Id)

<div class="mb-3">

@Html.LabelFor(m => m.Name, new { @class = "form-label" })


@Html.TextBoxFor(m => m.Name, new { @class = "form-control",
placeholder = "Enter employee name" })

@Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-


danger" })

</div>

<div class="mb-3">

@Html.LabelFor(m => m.Age, new { @class = "form-label" })

@Html.TextBoxFor(m => m.Age, new { @class = "form-control",


placeholder = "Enter employee age" })

@Html.ValidationMessageFor(m => m.Age, "", new { @class = "text-


danger" })

</div>

<div class="mb-3">

@Html.LabelFor(m => m.Department, new { @class = "form-label" })

@Html.TextBoxFor(m => m.Department, new { @class = "form-


control", placeholder = "Enter department" })

@Html.ValidationMessageFor(m => m.Department, "", new { @class =


"text-danger" })

</div>

<button type="submit" class="btn btn-primary">Save


Changes</button>

5. Custom CSS for Further Styling

You can add more custom styling by modifying the CSS section in the
layout file or by creating a separate CSS file. Here are some suggestions
to make the views more attractive:
body {

background-color: #e9ecef;

h2 {

margin-top: 20px;

color: #343a40;

text-transform: uppercase;

letter-spacing: 1px;

.table {

background-color: white;

box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.1);

.table th, .table td {

vertical-align: middle;

.btn-primary, .btn-success, .btn-danger {

width: 80px;

6. Bootstrap Icons

To make your UI more visually appealing, you can also add icons next to
buttons using Bootstrap Icons. Simply add the Bootstrap Icons CDN:

<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-
icons.css" rel="stylesheet">
Then, in your buttons:

<a href="@Url.Action("Edit", "Employee", new { id = employee.Id })"


class="btn btn-primary btn-sm">

<i class="bi bi-pencil"></i> Edit

</a>

<a href="@Url.Action("Delete", "Employee", new { id = employee.Id })"


class="btn btn-danger btn-sm">

<i class="bi bi-trash"></i> Delete

</a>

Explanation

Got it! Let's go line-by-line, explaining each word, why it’s used,
how it contributes to the flow of data, and what would happen if
certain parts were removed or done differently. I'll start with
EmployeeController.cs and then move on to
EmployeeRepository.cs and Employee.cs. This detailed
explanation will help you see the bigger picture of data flow
and the functionality of each line.

EmployeeController.cs
public class EmployeeController : Controller
 public: This keyword makes the EmployeeController class
accessible from anywhere in the application.
 class EmployeeController: Defines a class named
EmployeeController, which handles requests related to
employee operations.
 Controller: EmployeeController inherits from the
Controller class, which is part of ASP.NET MVC. It provides
methods like View(), RedirectToAction(), and
HttpNotFound() that are used to handle user requests and
generate responses.

private EmployeeRepository _employeeRepository = new


EmployeeRepository();
 private: Makes _employeeRepository accessible only
within this controller.
 EmployeeRepository _employeeRepository: Declares
a variable _employeeRepository of type
EmployeeRepository (a class responsible for database
interactions).
 = new EmployeeRepository();: Creates a new instance
of EmployeeRepository, allowing the controller to access
the methods defined in that class.
Data Flow:
 This instance is used throughout the controller to interact
with the database. Every time a method like
GetEmployeeById() or InsertEmployee() is called, the data
is sent from the controller to the repository and then to
the database.

Index Method (GET)


public ActionResult Index(int page = 1, int pageSize = 5, string
searchTerm = "")
 public: The method is accessible by the framework when
a request is made to the Index action.
 ActionResult: This is the return type of the method,
indicating that it will return a view or some kind of action
result (e.g., a redirection or a file download).
 Index: The name of the action method that handles
displaying the list of employees.
 int page = 1: Defines a parameter page that defaults to
1. It represents the current page number.
 int pageSize = 5: Defines a parameter pageSize that
defaults to 5. It represents how many employee records
will be displayed per page.
 string searchTerm = "": Defines a parameter
searchTerm that defaults to an empty string. It represents
a filter for searching employees by name, department,
etc.
Data Flow:
 When the user visits the employee list page, this method
is called. The page, pageSize, and searchTerm parameters
help retrieve only the required records based on
pagination and search filtering.

var (employees, totalRecords) =


_employeeRepository.GetPaginatedEmployees(page, pageSize,
searchTerm);
 var: Automatically infers the type from the right-hand side
of the assignment.
 (employees, totalRecords): Tuple that will hold two
values: a list of employees and the totalRecords (total
number of records in the database).
 _employeeRepository.GetPaginatedEmployees: Calls
the GetPaginatedEmployees() method from
EmployeeRepository, which executes a stored procedure
to fetch a specific page of employees and the total count.
 (page, pageSize, searchTerm): The method parameters
are passed to the repository to filter the employees based
on the page number, page size, and search term.
Data Flow:
 Data flows from the controller to the repository. The
repository will connect to the database, execute a stored
procedure, and return the employee records and total
count. The controller stores these values in employees and
totalRecords.

ViewBag.TotalRecords = totalRecords;
ViewBag.PageSize = pageSize;
ViewBag.CurrentPage = page;
ViewBag.SearchTerm = searchTerm;
 ViewBag: A dynamic object in MVC used to pass data
from the controller to the view. It doesn’t need to be
strongly typed.
 ViewBag.TotalRecords = totalRecords: Passes the
totalRecords value to the view. This will help the view in
rendering the total number of employees.
 ViewBag.PageSize = pageSize: Passes the pageSize to
the view so that the view knows how many records to
display per page.
 ViewBag.CurrentPage = page: Passes the page number
to the view, which will be used to display the current page.
 ViewBag.SearchTerm = searchTerm: Passes the
searchTerm to the view to display the current search filter.
Data Flow:
 Data retrieved from the repository (totalRecords,
pageSize, page, searchTerm) is passed to the view through
ViewBag. The view uses this data to show the paginated
list of employees with search functionality.
return View(employees);
 return View(employees): Returns the view to the user
and passes the list of employees to it. This list will be
rendered on the front-end (HTML page).
Data Flow:
 The employees data, which was retrieved from the
repository, is passed to the view for display.

Create Method (GET)


public ActionResult Create()
{
return View();
}
 public ActionResult Create(): This method is called
when the user navigates to the page for creating a new
employee.
 return View(): Returns a view (typically a form) for
creating a new employee.

Create Method (POST)


[HttpPost]
public ActionResult Create(Employee employee)
{
if (ModelState.IsValid)
{
_employeeRepository.InsertEmployee(employee);
return RedirectToAction("Index");
}
return View(employee);
}
 [HttpPost]: Indicates that this method will handle POST
requests (form submissions).
 public ActionResult Create(Employee employee):
This method accepts an Employee object that contains
data submitted from the form.
 ModelState.IsValid: Checks if the model (employee
data) is valid (e.g., no missing or invalid fields).
 _employeeRepository.InsertEmployee(employee):
Calls the InsertEmployee() method in the repository to
insert the employee into the database.
 RedirectToAction("Index"): After successfully creating
an employee, the user is redirected back to the Index
action to see the updated list.
 return View(employee): If the model is invalid (e.g.,
missing required fields), it returns the same form to the
user, along with the entered data, for correction.
Data Flow:
 The form data submitted by the user is captured in the
employee object. If the data is valid, it flows to the
repository where it is inserted into the database. Upon
success, the user is redirected to the employee list page.

Edit Method (GET)


public ActionResult Edit(int id)
{
var employee = _employeeRepository.GetEmployeeById(id);
if (employee == null)
{
return HttpNotFound();
}
return View(employee);
}
 public ActionResult Edit(int id): This method accepts
an id, which is the unique identifier for an employee.
 _employeeRepository.GetEmployeeById(id): Calls the
GetEmployeeById() method in the repository to fetch
employee data based on the provided id.
 if (employee == null): If the employee does not exist, it
returns a 404 error (HttpNotFound()).
 return View(employee): If the employee exists, the data
is passed to the view to display a form pre-filled with the
employee’s information.
Data Flow:
 The id flows from the user's request to the controller, then
to the repository to fetch the employee data. The
employee data flows back from the repository to the
controller, and then from the controller to the view.

Edit Method (POST)


[HttpPost]
public ActionResult Edit(Employee employee)
{
if (ModelState.IsValid)
{
_employeeRepository.UpdateEmployee(employee);
return RedirectToAction("Index");
}
return View(employee);
}
 [HttpPost]: Indicates that this method handles the POST
request for updating an employee.
 public ActionResult Edit(Employee employee): This
method takes an Employee object, which contains the
updated employee data.
 ModelState.IsValid: Ensures the submitted form data is
valid.
 _employeeRepository.UpdateEmployee(employee):
Calls the UpdateEmployee() method in the repository to
update the employee in the database.
 RedirectToAction("Index"): Upon successful update,
redirects the user to the employee list page.
 return View(employee): If the form data is invalid,
returns the form to the user with the entered data for
correction.
Data Flow:
 The updated employee data is sent to the repository to
update the record in the database. Upon success, the user
is redirected to the updated list.

Delete Method
public ActionResult Delete(int id)
{
_employeeRepository.SoftDeleteEmployee(id);
return RedirectToAction("Index");
}
 public ActionResult Delete(int id): Accepts an id
parameter, which represents the employee to be deleted.
 _employeeRepository.SoftDeleteEmployee(id): Calls
the SoftDeleteEmployee() method to mark the employee
as deleted without physically removing them from the
database.
 return RedirectToAction("Index"): Redirects the user to
the employee list after deletion.
Data Flow:
 The id flows from the controller to the repository. The
employee is marked as deleted, and the user is redirected
back to the employee list page.

This covers the controller! Let me know if you'd like similar


explanations for EmployeeRepository.cs and Employee.cs
or if you'd like further clarifications o
1. User Interaction (index.cshtml):
 The user visits the Employee list page for the first
time.
 Action Method Used: Index(int page = 1, int
pageSize = 5, string searchTerm = "")
o This action method is called by default when
the user accesses the controller without
specifying any specific action.
o It receives optional parameters for page
number, page size, and search term from the
query string or route data (depending on your
routing configuration).
 Why: This method handles the initial display of the
employee list with pagination. It retrieves the first
page (default page=1) of employee data based on
the default page size (pageSize=5) and any
provided search term (searchTerm).
2. Retrieving Paginated Employees with Search
(EmployeeRepository.GetPaginatedEmployees):
 Inside the Index action method:
o The method
_employeeRepository.GetPaginatedEmployees(
page, pageSize, searchTerm) is called.
o Stored Procedure Used:
GetPaginatedEmployees
 This stored procedure likely takes three
parameters: @PageNumber (integer),
@PageSize (integer), and @SearchTerm
(string, optional).
 Why: This SP handles fetching a specific
page of employee data considering
pagination and an optional search term. It
retrieves the requested page of
employees, potentially filtering them
based on the provided search term.

o What It Does:
 It returns a tuple containing two values:
 A list of Employee objects
representing the retrieved employee
data for the current page.
 The total number of employee records
in the database (used for pagination
calculations).
3. Populating the View with Retrieved Data
(index.cshtml):
 The Index action method receives the results from
GetPaginatedEmployees.
 It assigns the retrieved employee list (employees),
total records (totalRecords), current page number
(page), page size (pageSize), and search term
(searchTerm) to the ViewBag object.
 Why: The ViewBag object is used to temporarily
pass data from the controller to the view.
 The Index action then returns the index.cshtml
view.
 The index.cshtml view uses the data from the
ViewBag to:
o Display the list of employees in a table.
o Create the pagination controls based on the
total number of records, current page, and
page size.
o If a search term was provided, it displays the
search term in the view.
4. User Interaction (Search Functionality within
index.cshtml):
 The user enters a search term in the search form on
the index.cshtml page and submits the form.
5. Searching for Employees (Commented Out Option in
Controller):
 Action Method (Commented Out): Search(string
searchTerm) (though commented out, it provides
context for the previous user interaction)
o This action method would have been called
when the user submits the search form, but it's
currently commented out.
o Why (Commented Out): This functionality is
likely replaced by using the search term within
GetPaginatedEmployees.
o Commented Out SP (Contextual): This action
method previously might have utilized the
spSearchEmployees stored procedure (also
commented out in the repository).
6. User Interaction (Clicking Buttons):
 The user interacts with the buttons on the
index.cshtml page:
o "Add New Employee" button triggers a
navigation to the Create view for creating a
new employee.
o "Edit" link for a specific employee triggers
navigation to the Edit view for editing an
existing employee.
o "Delete" link for a specific employee triggers
deletion through the Delete action method.
7. Creating a New Employee:
 Action Method Used:
o Clicking "Add New Employee" calls the Create
action method (public ActionResult Create())
o Why: This method handles displaying the initial
form for creating a new employee.
o The Create action then returns the
create.cshtml view, which provides the form for
entering new employee details.

8. Submitting New Employee Details (Continued):


 Action Method Used: Create(Employee employee)
(HttpPost)
o This method retrieves the submitted employee
data from the form model (Employee).
o It performs model validation
(ModelState.IsValid). If validation fails, the
user is redirected back to the Create view with
the validation errors displayed.
o If validation passes, it calls the InsertEmployee
method of the EmployeeRepository with the
employee data. This method inserts the new
employee record into the database.
o On successful insertion, it redirects the user
back to the Index action to display the updated
employee list.
9. Editing an Existing Employee:
 Action Method Used: Edit(int id)
o This action method is called when the user
clicks the "Edit" link for a specific employee on
the index.cshtml page.
o It retrieves the employee ID from the route
data.
o It calls the GetEmployeeById method of the
EmployeeRepository with the ID. This method
retrieves the details of the specific employee.
o If the employee is found, it passes the
retrieved employee data to the edit.cshtml
view using the model.
o The edit.cshtml view then displays a form pre-
populated with the existing employee details.
10. Submitting Updated Employee Details:
 Action Method Used: Edit(Employee employee)
(HttpPost)
o This action method is called when the user
submits the updated employee form on the
edit.cshtml page.
o It retrieves the submitted employee data from
the form model (Employee).
o It performs model validation
(ModelState.IsValid). If validation fails, the
user is redirected back to the Edit view with
the validation errors displayed.
o If validation passes, it calls the
UpdateEmployee method of the
EmployeeRepository with the employee data.
This method updates the existing employee
record in the database.
o On successful update, it redirects the user back
to the Index action to display the updated
employee list.
11. Deleting an Employee:
 Action Method Used: Delete(int id)
o This action method is called when the user
clicks the "Delete" link for a specific employee
on the index.cshtml page.
o It retrieves the employee ID from the route
data.
o It calls the SoftDeleteEmployee method of the
EmployeeRepository with the ID. This method
likely performs a soft delete, such as setting a
flag in the database instead of permanently
removing the record.
o On successful deletion, it redirects the user
back to the Index action to display the updated
employee list.
In summary:
 The Index action method serves as the main entry
point for the employee list page, handling
pagination, search, and initial data retrieval.
 The Create, Edit, and Delete action methods handle
the CRUD operations for employees.
 The EmployeeRepository class interacts with the
database using stored procedures to retrieve,
insert, update, and delete employee data.
 The views (index.cshtml, create.cshtml, edit.cshtml)
are responsible for displaying the user interface,
handling form submissions, and displaying the
retrieved data.

You might also like