Model View Presenter

Separate the logic for the visual display from the event handling behaviour by putting them into two classes named as, the view and the presenter, respectively.

The view (the Web page or Web Part) manages the controls on the Web page and forwards user events to a presenter. The presenter contains the logic to respond to the events, updates the model (both the business logic and the application data), and alters the state of the view.

Step 1: Create an interface for a business object (Model). For example:
  1. public interface IModelStudent  
  2.     {  
  3.         IEnumerable<tbl_Student> StudentList();  
  4.         bool IsSuccessful { getset; }  
  5.         void AddStudent(tbl_Student student);  
  6.         void EditStudent(tbl_Student student);  
  7.         tbl_Student GetStudent(long StuID);  
  8.         void DeleteStudent(long StuID);  
  9.   
  10.     } 
Step 2: Create a class for Model
  1. public class ModelStudent : IModelStudent  
  2.    {  
  3.        StudentDBEntities db;  
  4.        //Custructor  
  5.        public ModelStudent()  
  6.        {  
  7.            db = new StudentDBEntities();  
  8.        }  
  9.        //List  
  10.        public IEnumerable<tbl_Student> StudentList()  
  11.        {  
  12.            return db.tbl_Student.ToList();  
  13.        }  
  14.        public bool IsSuccessful { getset; }  
  15.        public void AddStudent(tbl_Student student)  
  16.        {  
  17.            try  
  18.            {  
  19.                db.tbl_Student.AddObject(student);  
  20.                db.SaveChanges();  
  21.                IsSuccessful = true;  
  22.            }  
  23.            catch (Exception)  
  24.            {  
  25.                IsSuccessful = false;  
  26.            }  
  27.        }  
  28.        public void EditStudent(tbl_Student student)  
  29.        {  
  30.            try  
  31.            {  
  32.                tbl_Student originalStudent = db.tbl_Student.Where(w => w.StuID == student.StuID).Select(s => s).FirstOrDefault();  
  33.                db.tbl_Student.ApplyCurrentValues(student);  
  34.                db.SaveChanges();  
  35.                IsSuccessful = true;  
  36.            }  
  37.            catch  
  38.            {  
  39.                IsSuccessful = false;  
  40.            }  
  41.        }  
  42.        public tbl_Student GetStudent(long StuID)  
  43.        {  
  44.            return db.tbl_Student.Where(w => w.StuID == StuID).Select(s => s).First();  
  45.        }  
  46.        public void DeleteStudent(long StuID)  
  47.        {  
  48.            try  
  49.            {  
  50.                var student = db.tbl_Student.Where(w => w.StuID == StuID).Select(s => s).FirstOrDefault();  
  51.                db.tbl_Student.DeleteObject(student);  
  52.                db.SaveChanges();  
  53.                IsSuccessful = true;  
  54.            }  
  55.            catch (Exception)  
  56.            {  
  57.                IsSuccessful = false;  
  58.            }  
  59.        }  
  60.   
  61.    } 
Step 3: Create an interface for View
  1. public interface IViewStudent  
  2.     {  
  3.         long StuID { getset; }  
  4.         string StuName { getset; }  
  5.         int Age { getset; }  
  6.         IEnumerable<tbl_Student> students { getset; }  
  7.         tbl_Student studentDetails { getset; }  
  8.         event EventHandler LoadStudents;  
  9.         event EventHandler<EventArgs> AddStudent;  
  10.         event EventHandler<EventArgs> EditStudent;  
  11.         event EventHandler<EventArgs> GetStudent;  
  12.         event EventHandler<EventArgs> DeleteStudent;  
  13.     } 
Step 4: Create UI like below with a Label, TextBox and Button.CRUD operation
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StudentIndo.aspx.cs" Inherits="MVPDemo.StudentIndo" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title></title>  
  7. </head>  
  8. <body>  
  9.     <form id="form1" runat="server">  
  10.     <div>  
  11.         <asp:GridView ID="gvStudentList" runat="server" AutoGenerateColumns="false" ShowHeader="true">  
  12.             <Columns>  
  13.                 <asp:TemplateField HeaderText="Student Name">  
  14.                     <ItemTemplate>  
  15.                         <%-- <input id="hndID" runat="server" type="hidden" value='<%# Eval("StuID") %>' />--%>  
  16.                         <%# Eval("StuName") %>  
  17.                     </ItemTemplate>  
  18.                 </asp:TemplateField>  
  19.                 <asp:TemplateField HeaderText="Age">  
  20.                     <ItemTemplate>  
  21.                         <%# Eval("Age") %>  
  22.                     </ItemTemplate>  
  23.                 </asp:TemplateField>  
  24.                 <asp:TemplateField HeaderText="Edit">  
  25.                     <ItemTemplate>  
  26.                         <asp:LinkButton ID="lnkbtnEdit" runat="server" Text="Edit" OnClick="lnkbtnEdit_Click"  
  27.                             CommandArgument='<%# Eval("StuID") %>'></asp:LinkButton>  
  28.                     </ItemTemplate>  
  29.                 </asp:TemplateField>  
  30.                 <asp:TemplateField HeaderText="Delete">  
  31.                     <ItemTemplate>  
  32.                         <asp:LinkButton ID="lnkbtnDelete" runat="server" Text="Delete" OnClick="lnkbtnDelete_Click"  
  33.                             CommandArgument='<%# Eval("StuID") %>'></asp:LinkButton>  
  34.                     </ItemTemplate>  
  35.                 </asp:TemplateField>  
  36.             </Columns>  
  37.         </asp:GridView>  
  38.         <br />  
  39.         <br />  
  40.         <table>  
  41.             <tr>  
  42.                 <td>  
  43.                     Stu Name :  
  44.                 </td>  
  45.                 <td>  
  46.                     <input type="text" id="txtStuName" runat="server" placeholder="Enter Student Name"  
  47.                         required="required" aria-describedby="name-format" aria-required="true" />  
  48.                 </td>  
  49.             </tr>  
  50.             <tr>  
  51.                 <td>  
  52.                     Age :  
  53.                 </td>  
  54.                 <td>  
  55.                     <input type="text" id="txtAge" runat="server" placeholder="Enter Age" required="required"  aria-describedby="Age" aria-required="true" />  
  56.                 </td>  
  57.             </tr>  
  58.             <tr>  
  59.                 <td colspan="2">  
  60.                     <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />  
  61.                 </td>  
  62.             </tr>  
  63.         </table>  
  64.     </div>  
  65.     </form>  
  66. </body>  
  67. </html> 
Step 5: Create a Presenter class for collecting user inputs from View and pass view details to the Model.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using MVPDemo.Model;  
  6. using MVPDemo.View;  
  7. namespace MVPDemo.Presenter  
  8. {  
  9.     public class PresenterStudent  
  10.     {  
  11.         IViewStudent PView;  
  12.         IModelStudent PModel;  
  13.         public bool IsSuccessful  
  14.         {  
  15.             get { return PModel.IsSuccessful; }  
  16.         }  
  17.         public PresenterStudent(IViewStudent IView)  
  18.         {  
  19.             PView = IView;  
  20.             PModel = new ModelStudent();  
  21.             Initialize();  
  22.         }  
  23.         private void Initialize()  
  24.         {  
  25.             PView.LoadStudents += mView_LoadData;  
  26.             PView.AddStudent += new EventHandler<EventArgs>(mView_Save);  
  27.             PView.EditStudent += new EventHandler<EventArgs>(mView_Edit);  
  28.             PView.GetStudent += new EventHandler<EventArgs>(mView_GetStudent);  
  29.             PView.DeleteStudent += new EventHandler<EventArgs>(mView_DeleteStudent);  
  30.         }  
  31.   
  32.         //public IEnumerable<tbl_Student> LoadStudents()  
  33.         //{  
  34.         //    IEnumerable<tbl_Student> students = PModel.StudentList();  
  35.   
  36.         //    return students;  
  37.         //}  
  38.         //Load Studnt Data  
  39.         private void mView_LoadData(object sender, EventArgs e)  
  40.         {  
  41.             PView.students = PModel.StudentList();  
  42.         }  
  43.         // Save Student  
  44.         private void mView_Save(object sender, EventArgs e)  
  45.         {  
  46.             try  
  47.             {  
  48.                 tbl_Student student = new tbl_Student();  
  49.                 student.StuName = PView.StuName;  
  50.                 student.Age = PView.Age;  
  51.                 PModel.AddStudent(student);  
  52.             }  
  53.             catch (Exception)  
  54.             {  
  55.             }  
  56.         }  
  57.         //Edit Student  
  58.         private void mView_Edit(object sender, EventArgs e)  
  59.         {  
  60.             try  
  61.             {  
  62.                 tbl_Student student = new tbl_Student();  
  63.                 student.StuID = PView.StuID;  
  64.                 student.StuName = PView.StuName;  
  65.                 student.Age = PView.Age;  
  66.                 PModel.EditStudent(student);  
  67.             }  
  68.             catch (Exception)  
  69.             {  
  70.             }  
  71.         }  
  72.         //Get Student  
  73.         private void mView_GetStudent(object sender, EventArgs e)  
  74.         {  
  75.             try  
  76.             {  
  77.                 PView.studentDetails = PModel.GetStudent(PView.StuID);  
  78.             }  
  79.             catch (Exception)  
  80.             {  
  81.             }  
  82.         }  
  83.         private void mView_DeleteStudent(object sender, EventArgs e)  
  84.         {  
  85.             try  
  86.             {  
  87.                 PModel.DeleteStudent(PView.StuID);  
  88.             }  
  89.             catch (Exception)  
  90.             {  
  91.             }  
  92.         }  
  93.     }  

Step 6: Code-behind of ASPX page - View is communicating to the Model via Presenter
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using MVPDemo.Model;  
  8. using MVPDemo.View;  
  9. using MVPDemo.Presenter;  
  10. namespace MVPDemo  
  11. {  
  12.     public partial class StudentIndo : System.Web.UI.Page, IViewStudent  
  13.     {  
  14.         PresenterStudent PStudent;  
  15.         public long StuID { getset; }  
  16.         public string StuName  
  17.         {  
  18.             get { return txtStuName.Value; }  
  19.             set { txtStuName.Value = value; }  
  20.         }  
  21.         public int Age  
  22.         {  
  23.             get { return Convert.ToInt32(txtAge.Value); }  
  24.             set { txtAge.Value = value.ToString(); }  
  25.         }  
  26.         public IEnumerable<tbl_Student> students { getset; }  
  27.         public tbl_Student studentDetails { getset; }  
  28.         public event EventHandler LoadStudents;  
  29.         public event EventHandler<EventArgs> AddStudent;  
  30.         public event EventHandler<EventArgs> EditStudent;  
  31.         public event EventHandler<EventArgs> GetStudent;  
  32.         public event EventHandler<EventArgs> DeleteStudent;  
  33.         //  
  34.         public StudentIndo()  
  35.         {  
  36.             PStudent = new PresenterStudent(this);  
  37.         }  
  38.         protected void Page_Load(object sender, EventArgs e)  
  39.         {  
  40.             if (!IsPostBack)  
  41.             {  
  42.                 BindData();  
  43.   
  44.             }  
  45.         }  
  46.         private void clearControl()  
  47.         {  
  48.             txtStuName.Value = "";  
  49.             txtAge.Value = "";  
  50.         }  
  51.         private void BindData()  
  52.         {  
  53.             this.LoadStudents(thisnew EventArgs());  
  54.             gvStudentList.DataSource = this.students;  
  55.             gvStudentList.DataBind();  
  56.         }  
  57.         protected void btnSave_Click(object sender, EventArgs e)  
  58.         {  
  59.             if (btnSave.Text == "Save")  
  60.             {  
  61.                 if (this.AddStudent != null)  
  62.                 {  
  63.                     this.AddStudent(this, EventArgs.Empty);  
  64.                 }  
  65.             }  
  66.             else  
  67.             {  
  68.                 if (ViewState["StuID"] != null)  
  69.                 {  
  70.                     StuID = Convert.ToInt64(ViewState["StuID"]);  
  71.                 }  
  72.                 this.EditStudent(this, EventArgs.Empty);  
  73.                 btnSave.Text = "Save";  
  74.             }  
  75.             BindData();  
  76.             clearControl();  
  77.         }  
  78.         protected void lnkbtnEdit_Click(object sender, EventArgs e)  
  79.         {  
  80.             LinkButton lnkbtn = sender as LinkButton;  
  81.             ViewState["StuID"] = StuID = Convert.ToInt64(lnkbtn.CommandArgument);  
  82.             this.GetStudent(this, EventArgs.Empty);  
  83.             StuName = this.studentDetails.StuName;  
  84.             Age = this.studentDetails.Age;  
  85.             btnSave.Text = "Update";  
  86.             // setData();  
  87.   
  88.         }  
  89.         protected void lnkbtnDelete_Click(object sender, EventArgs e)  
  90.         {  
  91.             LinkButton lnkbtnDelete = sender as LinkButton;  
  92.             StuID = Convert.ToInt64(lnkbtnDelete.CommandArgument);  
  93.             this.DeleteStudent(this, EventArgs.Empty);  
  94.             BindData();  
  95.   
  96.         }  
  97.     }  

Happy MVP Coding!!!

Next Recommended Reading Return Multiple Models to View In MVC