Model-View-Presenter(MVP)
In this demo you will find, how to create the
CRUD in the asp.net using MVP pattern.
Remember; -
Model: - Used for defining Business Logic, DB Call.
View: - Used for defining page controls as
a property using Interface.
Presenter: - Used for defining co-ordination with Model
& View.
Note: - View cannot access the Model
directly.
Let
Start
Step 1: - Open Visual
Studio 2015 => Go to File Menu => New => Project...
Step 2: - In the
Installed Templates list, select Visual C# => Web
Step 3: -
Select ASP.Net Web Application (.NET Framework) from the Web
list => Type MVP_CRUD_Application in the Name box and click
OK
Step 4: -
Select Empty template from ASP.NET Templates List and
Check Web Forms check box under Add folders and core
references for:
Step 5: - After clicking OK, project structure look like below.
Step 6: - Add View and Presenter folder inside
the solution, Models folder
already there.
Step 7: - Right Click on Project Root folder
=> Add => New Items... => Expand Visual C# from
Left Pane and Select Web =>
Select Web
Form from Middle Pane => Type Employee.aspx in
Name box => Click Add
Copy Past following html in the Employee.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Employee</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<link rel="stylesheet" href="/resources/demos/style.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#txtDOB").datepicker();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table border="1">
<caption><b>Create Employee</b></caption>
<tr>
<td><b>Name</b></td>
<td>
<asp:HiddenField ID="hdnEmpId" runat="server" Value=""></asp:HiddenField>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td><b>Gender</b></td>
<td>
<asp:RadioButtonList ID="rblGender" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="M">Male</asp:ListItem>
<asp:ListItem Value="F">Female</asp:ListItem>
<asp:ListItem Value="O">Other</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td><b>Date of Birth</b></td>
<td>
<asp:TextBox ID="txtDOB" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td><b>Email Id</b></td>
<td>
<asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td><b>Mobile No</b></td>
<td>
<asp:TextBox ID="txtMobileNo" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td><b>Department</b></td>
<td>
<asp:DropDownList ID="ddlDepartment" runat="server">
<asp:ListItem Value="">Select</asp:ListItem>
<asp:ListItem Value="1">IT</asp:ListItem>
<asp:ListItem Value="2">Admin</asp:ListItem>
<asp:ListItem Value="3">Finance</asp:ListItem>
<asp:ListItem Value="4">Sales</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td><b>City</b></td>
<td>
<asp:DropDownList ID="ddlCity" runat="server">
<asp:ListItem Value="">Select</asp:ListItem>
<asp:ListItem Value="1">Mumbai</asp:ListItem>
<asp:ListItem Value="2">Delhi</asp:ListItem>
<asp:ListItem Value="3">Kolkatta</asp:ListItem>
<asp:ListItem Value="4">Chennai</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
|
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:GridView ID="gvEmployee" runat="server"
EmptyDataText="No Record available
to display."
AutoGenerateColumns="false"
CellPadding="4" ForeColor="#333333" GridLines="Both">
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Gender" DataField="GenderName" />
<asp:BoundField HeaderText="Date Of Birth" DataField="DOB" />
<asp:BoundField HeaderText="Email Id" DataField="EmailId" />
<asp:BoundField HeaderText="Mobile No" DataField="MobileNo" />
<asp:BoundField HeaderText="Department" DataField="DepartmentName" />
<asp:BoundField HeaderText="City" DataField="CityName" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="linkBtnEdit" runat="server" empId='<%#Eval("Id") %>' OnClick="linkBtnEdit_Click">Edit</asp:LinkButton>
|
<asp:LinkButton ID="linkBtnDelete" runat="server" empId='<%#Eval("Id") %>' OnClick="linkBtnDelete_Click">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Note for next step: -
1. Add property for GridView in the EmployeeGridView.
2. Add property for Employee From controls in
the IEmployeeView.
Step 8: - Right Click on Models folder
=> Add => New Items... => Expand Visual C# from Left
Pane and Select Code => Select Class from
Middle Pane => Type EmployeeGridView.cs in Name box
=> Click Add
Copy Past following code in the EmployeeGridView.cs
using System;
public class EmployeeGridView
{
public string Id { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string GenderName { get; set; }
public DateTime DOB { get; set; }
public string EmailId { get; set; }
public string MobileNo { get; set; }
public string Department { get; set; }
public string DepartmentName { get; set; }
public string City { get; set; }
public string CityName { get; set; }
}
Step 9: - Right Click on View folder =>
Add => New Items... => Expand Visual C# from Left Pane
and Select Code => Select Interface from
Middle Pane => Type IEmployeeView.cs in Name box =>
Click Add
Copy Past following code in the IEmployeeView.cs
using MVP_CRUD_Application.Models;
using System.Collections.Generic;
public interface IEmployeeView
{
string Id { get; set; }
string Name { get; set; }
string Gender { get; set; }
string DOB { get; set; }
string EmailId { get; set; }
string MobileNo { get; set; }
string Department { get; set; }
string City { get; set; }
List<EmployeeGridView> GridView { get; set; }
}
Note for next step: -
1. Add IEmployeeModel & EmployeeModel that communicate
with database.
2. Add EmployeePresenter that communicate with
Models and View.
Step 10: - Right Click on Models folder
=> Add => New Items... => Expand Visual C# from Left
Pane and Select Code => Select Interface from
Middle Pane => Type IEmployeeModel.cs in Name box
=> Click Add
Copy Past following code in the IEmployeeModel.cs
using MVP_CRUD_Application.View;
using System.Collections.Generic;
public interface IEmployeeModel
{
int SaveEmployee(IEmployeeView item);
int UpdateEmployee(IEmployeeView item);
int DeleteEmployee(IEmployeeView item);
List<EmployeeGridView> SelectEmployee();
EmployeeGridView SelectEmployeeById(IEmployeeView item);
}
Step 11: - Right Click on Models folder
=> Add => New Items... => Expand Visual C# from Left
Pane and Select Code => Select Class from
Middle Pane => Type EmployeeModel.cs in Name box
=> Click Add
Copy Past following code in the EmployeeModel.cs
using MVP_CRUD_Application.View;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public class EmployeeModel : IEmployeeModel
{
private SqlConnection _con = new SqlConnection(ConfigurationManager.ConnectionStrings["Default"].ConnectionString);
private DataSet _dataset = null;
private int _flag;
public int SaveEmployee(IEmployeeView item)
{
try
{
using (SqlCommand cmd = new SqlCommand())
{
_con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "proc_SaveEmployee";
cmd.Connection = _con;
cmd.Parameters.AddWithValue("@Name", item.Name);
cmd.Parameters.AddWithValue("@Gender", item.Gender);
cmd.Parameters.AddWithValue("@DOB", Convert.ToDateTime(item.DOB).ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("@EmailId", item.EmailId);
cmd.Parameters.AddWithValue("@MobileNo", item.MobileNo);
cmd.Parameters.AddWithValue("@Department", item.Department);
cmd.Parameters.AddWithValue("@City", item.City);
_flag = cmd.ExecuteNonQuery();
_con.Close();
}
return _flag;
}
catch (Exception ex)
{
throw ex;
}
}
public int UpdateEmployee(IEmployeeView item)
{
try
{
using (SqlCommand cmd = new SqlCommand())
{
_con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "proc_UpdateEmployee";
cmd.Connection = _con;
cmd.Parameters.AddWithValue("@Id", item.Id);
cmd.Parameters.AddWithValue("@Name", item.Name);
cmd.Parameters.AddWithValue("@Gender", item.Gender);
cmd.Parameters.AddWithValue("@DOB", Convert.ToDateTime(item.DOB).ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("@EmailId", item.EmailId);
cmd.Parameters.AddWithValue("@MobileNo", item.MobileNo);
cmd.Parameters.AddWithValue("@Department", item.Department);
cmd.Parameters.AddWithValue("@City", item.City);
_flag = cmd.ExecuteNonQuery();
_con.Close();
}
return _flag;
}
catch (Exception ex)
{
throw ex;
}
}
public int DeleteEmployee(IEmployeeView item)
{
try
{
using (SqlCommand cmd = new SqlCommand())
{
_con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "proc_DeleteEmployee";
cmd.Connection = _con;
cmd.Parameters.AddWithValue("@Id", item.Id);
_flag = cmd.ExecuteNonQuery();
_con.Close();
}
return _flag;
}
catch (Exception ex)
{
throw ex;
}
}
public List<EmployeeGridView> SelectEmployee()
{
List<EmployeeGridView> employeeList = null;
try
{
using (SqlCommand cmd = new SqlCommand())
{
_con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "proc_SelectEmployeeList";
cmd.Connection = _con;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
_dataset = new DataSet();
da.Fill(_dataset);
}
_con.Close();
}
if
(_dataset.Tables[0].Rows.Count > 0)
{
var jsonString = JsonConvert.SerializeObject(_dataset.Tables[0]);
employeeList = JsonConvert.DeserializeObject<List<EmployeeGridView>>(jsonString);
}
return employeeList;
}
catch (Exception ex)
{
throw ex;
}
}
public EmployeeGridView SelectEmployeeById(IEmployeeView item)
{
EmployeeGridView employee = null;
try
{
using (SqlCommand cmd = new SqlCommand())
{
_con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "proc_SelectEmployee";
cmd.Connection = _con;
cmd.Parameters.AddWithValue("@Id", item.Id);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
_dataset = new DataSet();
da.Fill(_dataset);
}
_con.Close();
}
if
(_dataset.Tables[0].Rows.Count > 0)
{
var jsonString = JsonConvert.SerializeObject(_dataset.Tables[0]).Replace("[", "").Replace("]", "");
employee = JsonConvert.DeserializeObject<EmployeeGridView>(jsonString);
}
return employee;
}
catch (Exception ex)
{
throw ex;
}
}
}
Step 12: - Right Click on Presenter folder
=> Add => New Items... => Expand Visual C# from Left
Pane and Select Code => Select Class from
Middle Pane => Type EmployeePresenter.cs in Name box
=> Click Add
Copy Past following code in the EmployeePresenter.cs
using MVP_CRUD_Application.Models;
using MVP_CRUD_Application.View;
public class EmployeePresenter
{
private IEmployeeModel _model;
private IEmployeeView _view;
public EmployeePresenter(IEmployeeView view)
{
_view
= view;
}
public void SaveEmployee()
{
_model = new EmployeeModel();
_model.SaveEmployee(_view);
ClearField();
}
public void UpdateEmployee()
{
_model = new EmployeeModel();
_model.UpdateEmployee(_view);
ClearField();
}
public void DeleteEmployee()
{
_model = new EmployeeModel();
_model.DeleteEmployee(_view);
}
public void SelectEmployee()
{
_model = new EmployeeModel();
_view.GridView = _model.SelectEmployee();
}
public void SelectEmployeeById()
{
_model = new EmployeeModel();
EmployeeGridView employeeGridView =
_model.SelectEmployeeById(_view);
_view.Id = employeeGridView.Id;
_view.Name = employeeGridView.Name;
_view.Gender = employeeGridView.Gender;
_view.DOB = employeeGridView.DOB.ToString("MM/dd/yyyy");
_view.EmailId = employeeGridView.EmailId;
_view.MobileNo = employeeGridView.MobileNo;
_view.Department = employeeGridView.Department;
_view.City = employeeGridView.City;
}
private void ClearField()
{
_view.Id
= "";
_view.Name = "";
_view.Gender = "";
_view.DOB = "";
_view.EmailId = "";
_view.MobileNo = "";
_view.Department = "";
_view.City = "";
}
}
Step 13: - Open Employee.aspx.cs file =>
Inherit the IEmployeeView interface =>Implement the IEmployeeView interface
property.
Copy Past following code in the Employee.aspx.cs
using MVP_CRUD_Application.Models;
using MVP_CRUD_Application.Presenter;
using MVP_CRUD_Application.View;
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
public partial class Employee : System.Web.UI.Page, IEmployeeView
{
private EmployeePresenter _presenter;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
_presenter = new EmployeePresenter(this);
_presenter.SelectEmployee();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
_presenter = new EmployeePresenter(this);
_presenter.SaveEmployee();
_presenter.SelectEmployee();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
_presenter = new EmployeePresenter(this);
_presenter.UpdateEmployee();
_presenter.SelectEmployee();
}
protected void linkBtnEdit_Click(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
string empId = btn.Attributes["empId"];
Id =
empId;
_presenter = new EmployeePresenter(this);
_presenter.SelectEmployeeById();
}
protected void linkBtnDelete_Click(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
string empId = btn.Attributes["empId"];
Id =
empId;
_presenter = new EmployeePresenter(this);
_presenter.DeleteEmployee();
_presenter.SelectEmployee();
}
#region Form Properties
public string City
{
get { return ddlCity.SelectedValue; }
set { ddlCity.ClearSelection();
ddlCity.SelectedValue = value; }
}
public string Department
{
get { return
ddlDepartment.SelectedValue; }
set {
ddlDepartment.ClearSelection(); ddlDepartment.SelectedValue = value; }
}
public string DOB
{
get { return txtDOB.Text; }
set { txtDOB.Text = value; }
}
public string EmailId
{
get { return txtEmailId.Text; }
set { txtEmailId.Text = value; }
}
public string Gender
{
get { return rblGender.SelectedValue; }
set {
rblGender.ClearSelection(); rblGender.SelectedValue = value; }
}
public List<EmployeeGridView> GridView
{
get { return (List<EmployeeGridView>)gvEmployee.DataSource;
}
set { gvEmployee.DataSource = value; gvEmployee.DataBind(); }
}
public string Id
{
get { return hdnEmpId.Value; }
set { hdnEmpId.Value = value; }
}
public string MobileNo
{
get { return txtMobileNo.Text; }
set { txtMobileNo.Text = value; }
}
public string Name
{
get { return txtName.Text; }
set { txtName.Text = value; }
}
#endregion
}
Step 14: - DB Script
Copy Past Script in SQLQuery Window and Run Script
CREATE DATABASE MVP
GO
USE MVP
GO
CREATE TABLE dbo.Employee
(
Id INT
IDENTITY
,Name
VARCHAR(50) NOT NULL
,Gender
CHAR(1) NOT NULL
,DOB
DATE NOT NULL
,EmailId
VARCHAR(50) NOT NULL
,MobileNo
VARCHAR(10) NOT NULL
,Department
TINYINT NOT NULL
,City
TINYINT NOT NULL
)
GO
CREATE TABLE dbo.Department
(
Id INT
IDENTITY
,Name
VARCHAR(50) NOT NULL
)
GO
INSERT INTO dbo.Department(Name)VALUES('IT'),('Admin'),('Finance'),('Sales')
GO
CREATE TABLE dbo.City
(
Id INT
IDENTITY
,Name
VARCHAR(50) NOT NULL
)
GO
INSERT INTO dbo.City(Name)VALUES('Mumbai'),('Delhi'),('Kolkatta'),('Chennai')
GO
CREATE PROCEDURE dbo.proc_SaveEmployee
(
@Name VARCHAR(50)
,@Gender
VARCHAR(10)
,@DOB
VARCHAR(10)
,@EmailId
VARCHAR(50)
,@MobileNo
VARCHAR(10)
,@Department
VARCHAR(20)
,@City
VARCHAR(20)
)
AS
BEGIN
INSERT
INTO dbo.Employee (Name,Gender,DOB,EmailId,MobileNo,Department,City)
VALUES
(@Name,@Gender,@DOB,@EmailId,@MobileNo,@Department,@City)
END
GO
CREATE PROCEDURE dbo.proc_UpdateEmployee
(
@Id INT
,@Name
VARCHAR(50)
,@Gender
VARCHAR(10)
,@DOB
VARCHAR(10)
,@EmailId
VARCHAR(50)
,@MobileNo
VARCHAR(10)
,@Department
VARCHAR(20)
,@City
VARCHAR(20)
)
AS
BEGIN
UPDATE
dbo.Employee
SET Name =
@Name
,Gender =@Gender
,DOB = @DOB
,EmailId = @EmailId
,MobileNo = @MobileNo
,Department =
@Department
,City = @City
WHERE
Id = @Id
END
GO
CREATE PROCEDURE dbo.proc_DeleteEmployee
(
@Id INT
)
AS
BEGIN
DELETE
FROM
dbo.Employee
WHERE
Id = @Id
END
GO
CREATE PROCEDURE dbo.proc_SelectEmployeeList
AS
BEGIN
SELECT
E.Id,E.Name,E.Gender
,CASE WHEN E.Gender = 'M' THEN 'Male'
WHEN E.Gender = 'F' THEN 'Female'
WHEN E.Gender = 'O' THEN 'Other'
END 'GenderName'
,E.DOB,E.EmailId,E.MobileNo,E.Department,D.Name'DepartmentName'
,E.City,C.Name'CityName'
FROM
dbo.Employee E
INNER
JOIN dbo.Department
D ON E.Department
= D.Id
INNER
JOIN dbo.City C
ON E.City = C.Id
END
GO
CREATE PROCEDURE dbo.proc_SelectEmployee
(
@Id INT
)
AS
BEGIN
SELECT
E.Id,E.Name,E.Gender
,CASE WHEN E.Gender = 'M' THEN 'Male'
WHEN E.Gender = 'F' THEN 'Female'
WHEN E.Gender = 'O' THEN 'Other'
END 'GenderName'
,E.DOB,E.EmailId,E.MobileNo,E.Department,D.Name'DepartmentName'
,E.City,C.Name'CityName'
FROM
dbo.Employee E
INNER
JOIN dbo.Department
D ON E.Department
= D.Id
INNER
JOIN dbo.City C
ON E.City = C.Id
WHERE
E.Id = @Id
END
GO
CREATE PROCEDURE dbo.proc_SelectDepartmentList
AS
BEGIN
SELECT
*
FROM
dbo.Department
END
GO
CREATE PROCEDURE dbo.proc_SelectCityList
AS
BEGIN
SELECT
*
FROM
dbo.City
END
GO
ALL Done
RUN Project
Output