Click here to Skip to main content
15,886,110 members
Articles / Web Development / ASP.NET

Working with SQL Server using the MVP Pattern

Rate me:
Please Sign up or sign in to vote.
2.64/5 (5 votes)
10 Dec 2013CPOL2 min read 19.5K   269   8   1
Working with SQL Server in an ASP.NET application using the MVP Pattern.

What is MVP?

The MVP design pattern is an Architecture Pattern used to build ASP.NET applications. It refers to splitting up the responsibilities for gathering, displaying, and storing information from a web page into separate objects: a Model object, a View object, and a Presenter object. The View is often an interface which is then implemented by an ASP.NET web page; the Model is a business object. The Presenter negotiates the transfer of data between the other two objects.

Image 1

  • View: View can be your ASPX page in your web application.
  • Model: Model contains all the business logic.
  • Presenter: Presenter is an intermediate between the Model and the View. It binds the View with the Model.

Getting Started

Step 1

Create folders Model, Presenter, and View in the project as shown in the figure:

Image 2

Step 2

Create a new interface called IModel inside the Model folder to add the following code:

C#
public interface IModel
{
    List<String> setInfo();
}

Step 3

Create a new class inside the Model folder and add the following code:

C#
class Model : IModel
{
    // Adding Text to Label.
    public List<String> setInfo()
    {
        List<String> l = new List<string>();
        l.Add("ID:");
        l.Add("First Name:");
        l.Add("Last Name:");
        l.Add("Email Id:");
        l.Add("Phone No:");
        l.Add("Submit");
        l.Add("Data saved successfully.");
        return l;
    }
}

Note: We are adding string parameter - this string parameter will set to the Label in the ASPX page.

Step 4

Next moving to the View folder, create a new interface called IView and add the following code:

C#
public interface IView
{
    string EmpIDLabel { get; set; }
    string EmpFirstNameLabel { get; set; }
    string EmpLastNameLabel { get; set; }
    string EmpMaildIDLabel { get; set; }
    string EmpPhoneNoLabel { get; set; }
    string EmpIDTextBox { get; set; }
    string EmpFirstNameTextBox { get; set; }
    string EmpLastNameTextBox { get; set; }
    string EmopMailIDTextBox { get; set; }
    string EmpPhoneNoTextBox { get; set; }
    string EmpButtonText { get; set; }
    string SuccessLabel { get; set; }
}

Step 5

Next, moving to the Presenter folder, create a new class called Presenter to add the following code:

C#
public class Presenter
{
    IView _pView;
    IModel _pModel;

    public Presenter(IView PView, IModel PModel)
    {
        _pView = PView;
        _pModel = PModel;
    }

    // Here we are binding the string data to ASPX Label from the Model.
    public void BindModalView()
    {
        List<String> ls = _pModel.setInfo();
        _pView.EmpIDLabel = ls[0];
        _pView.EmpFirstNameLabel = ls[1];
        _pView.EmpLastNameLabel = ls[2];
        _pView.EmpMaildIDLabel = ls[3];
        _pView.EmpPhoneNoLabel = ls[4];
        _pView.EmpButtonText = ls[5];
    }

    // Inserting data to database table 
    string connection = 
      @"Data Source=RAVINDRA\MSSQLSERVERS;Initial Catalog=CrudMethod;Integrated Security=SSPI;";
    public void Save()
    {
        SqlConnection con = new SqlConnection(connection);
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandText = "INSERT INTO Employee(Id,FirstName,LastName," + 
          "EmailId,phoneNo)VALUES(@Id,@FirstName,@LastName,@EmailId,@PhoneNo)";
        cmd.Parameters.AddWithValue("@Id", int.Parse(_pView.EmpIDTextBox));
        cmd.Parameters.AddWithValue("@FirstName", _pView.EmpFirstNameTextBox);
        cmd.Parameters.AddWithValue("@LastName", _pView.EmpLastNameTextBox);
        cmd.Parameters.AddWithValue("@EmailId", _pView.EmopMailIDTextBox);
        cmd.Parameters.AddWithValue("@PhoneNo", int.Parse(_pView.EmpPhoneNoTextBox));
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            List<String> ls = _pModel.setInfo();
            _pView.SuccessLabel = ls[6]; // assigning the string from Model to the Label.
        }
        catch (SqlException ex)
        {

            throw ex;
        }
        finally
        {
            con.Close();
        }
    }
}

Step 6

Next step, add the following HTML code to your default.aspx page:

ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" 
               CodeBehind="Default.aspx.cs" Inherits="MVPDemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
           "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>MVP Demo</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <center>
    <h2>MVP Pattern Demo</h2>
        <table>
            <tr>
                <td>
                    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtID" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="Label3" runat="server" Text=""></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
            <td>
             <asp:Label ID="Label4" runat="server" Text=""></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtEmailID" runat="server"></asp:TextBox>
            </td>
            </tr>
            <tr>
            <td>
            <asp:Label ID="Label5" runat="server" Text=""></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtPhoneNo" runat="server"></asp:TextBox>
            </td>
            </tr>
            <tr>
            <td colspan="2" align="center">
                <asp:Button ID="btnSubmit" runat="server" 
                Text="" onclick="btnSubmit_Click" />
            </td>
            </tr>
            <tr>
            <td>
            <asp:Label ID="Label6" runat="server" 
            Text="" ForeColor="Green"></asp:Label>
            </td>
            </tr>
        </table>
        </center>
    </div>
    </form>
</body>
</html>

Step 7

Next, in the Default.aspx.cs page, add the View members. Here we are assigning the Label and TexBox values to the View members.

C#
#region IView Members
public string EmpIDLabel
{
    get
    {
        return Label1.Text;
    }
    set
    {
        Label1.Text = value;
    }
}
public string EmpFirstNameLabel
{
    get
    {
        return Label2.Text;
    }
    set
    {
        Label2.Text = value;
    }
}

public string EmpLastNameLabel
{
    get
    {
        return Label3.Text;
    }
    set
    {
        Label3.Text = value;
    }
}
public string EmpMaildIDLabel
{
    get
    {
        return Label4.Text;
    }
    set
    {
        Label4.Text = value;
    }
}
public string EmpPhoneNoLabel
{
    get
    {
        return Label5.Text;
    }
    set
    {
         Label5.Text = value;
    }
}
public string EmpIDTextBox
{
    get
    {
        return txtID.Text;
    }
    set
    {
        txtID.Text = value;
    }
}
public string EmpFirstNameTextBox
{
    get
    {
        return txtFirstName.Text;
    }
    set
    {
        txtFirstName.Text = value;
    }
}
public string EmpLastNameTextBox
{
    get
    {
        return txtLastName.Text;
    }
    set
    {
        txtLastName.Text = value;
    }
}
public string EmopMailIDTextBox
{
    get
    {
        return txtEmailID.Text;
    }
    set
    {
        txtEmailID.Text = value;
    }
}
public string EmpPhoneNoTextBox
{
    get
    {
        return txtPhoneNo.Text;
    }
    set
    {
        txtPhoneNo.Text = value;
    }
}
public string EmpButtonText
{
    get
       {
        return btnSubmit.Text;
    }
    set
    {
        btnSubmit.Text = value;
    }
}
public string SuccessLabel
{
    get
    {
        return Label6.Text;
    }
    set
    {
        Label6.Text = value;
    }
}

#endregion

Step 8

In Page Load, call the Presenter class and call BindModalView() to set the text to the ASPX label from the Model.

C#
protected void Page_Load(object sender, EventArgs e)
{
    // Bind the data to the view from Presenter. 
    Presenter p = new Presenter(this, new MVPDemo.Model());
    p.BindModalView();
}

Step 9

In the button click event, add the following code to insert the data to the table.

C#
protected void btnSubmit_Click(object sender, EventArgs e)
{
    // Inserting data to the database table.
    Presenter p = new Presenter(this, new MVPDemo.Model());
    p.Save();
}

Step 10

Finally, the ASPX of the result page looks like this:

Image 3

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
Questionclassification of objects Pin
Member 120288542-Oct-15 9:08
Member 120288542-Oct-15 9:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.