Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Implementation of MVC Patterns in ASP.NET Web forms Application.

0.00/5 (No votes)
3 Oct 2013 1  
This tutorial describe the MVC Pattern and also describe how to implement MVC pattern in ASP.Net web forms application.

Introduction

This tutorial describe the MVC Pattern with diagram for both technical’s and non- technical’s. This tutorial also shows how to implement MVC pattern in ASP.NET web forms application with example.

Contents

  • Part1: Introduction of Active Model MVC Pattern.
  • Part2: Sample ASP.NET Web Forms project using MVC Pattern.

Part 1: Introduction of Active Model MVC Pattern

What is Design Pattern?

According to my concept, patterns are solutions of recurrent problem in software development. Patterns are implemented using Object Oriented Principles. It is an approved solution of a particular problem. For example Observer pattern is used to notify the dependents of an object, on which the dependents are, depend on. And Observer pattern is used in MVC implementation.

What is MVC?

Model View Controller (MVC) is popular UI design pattern. It is used to represent the Presentation layer. This pattern separates the application codes. MVC pattern has three components, named Model, View and Controller. The following pictorial representation shows the components of MVC pattern and there’s relationship, and will make it clear even non-technical readers.

Figure: Components of MVC Pattern and theirs relationship (Non-technical Notations)

The above diagram clearly shows the main component of MVC and their relationship. Let’s describe in details.

View: View represents the user interface. The data it shows gets form Model Component. View gets updated notification from Model when Model is updated by controller.

  • Controller: Controller acts as intermediate between View and Model. When user fires an event, then View receives it and handover the control to Controller. Then Controller checks for data validation and if valid then it updates the Model. It also updates the View it needed.
  • Model: Model contains data for the Application. When Model data is changed by Controller, then Model notifies the View about update and then View get update data from Model and update the UI.

The following diagram is the UML Class Diagram of MVC pattern.

Figure: Components of MVC Pattern and theirs relationship (Technical Notations).

The above diagram shows the class and relationship between them. Here Controller and View Class have bi-directional relationship. Also Model and View has bi-directional relationship and Controller and Model has one way relationship.

The following diagram shows the sequence diagram for MVC Pattern.

Figure: Sequence diagram of MVC Pattern.

The above sequence diagram starts from User request, when User fires an event on UI. The View sends RequestUpdate message to Controller, passing itself as a parameter. Controller send UpdateData message to Model with the updated value as a parameter. After update the Model itself, it notifies the View using NotifyUpdate message, with passing itself as a parameter. After notified, the view updates the UI with the updated value and gets the update value from Model.

This was all about the MVC patterns and its components model and how they interact using method call.

Part 2: Sample ASP.NET Web Forms project using MVC Pattern

Overview

The following screen shots provide a quick view of the ASP.NET Web forms application that I am going to explain. When you run the application from Visual Studio, you will see the following output.

Description of the Project

The sample application shows the Default Windows Operating System Configuration Requirements and one can update the configurations.

So, now the time to go deep in the Project step by step.

  1. Create an ASP.NET Web Forms Project shown in the following Solution Explorer’s Screen shot.

Description: In the project I have newly created three folders named Controllers, Models and Views to separately place the Controller, Model and View classes respectively.

2. Create a Controller class in file Windows98Controller.cs. The following code shows the Controller class.

public class Window98Controller
{
    private Window98Model Model;
    private Windows98View View;
    public Window98Controller(Window98Model paramModel, Windows98View paramView)
    {
        Model = paramModel;
        View = paramView;
    }
    public void InitializedConponent(bool ispostback)
    {
        if(!ispostback)
            View.InitializedView(Model);
    }
    public Window98Controller()
    {
    }
    public void RequestUpdate(Windows98View view)
    {
        if (Model != null)
        {
           Model.UpdateModel(view.Ram,view.Disk,view.CPUSpeed);
        }
    }
}

Description: The Constructor Window98Controller (Window98Model paramModel, Windows98View paramView) is used to pass Model and View to Controller to make relationship between them at compile time and to initialize the values. The RequestUpdate () method is called by View and it calls the UpdateModel () method of Model.

3. Create a Model class in file Windows98Model.cs. The following code shows the Model class

public class Window98Model
{
    private ArrayList aList = new ArrayList();
    public Window98Model(string paramName,decimal paramMinRam,
        decimal paramMinDisk, decimal    paramCpuSpeedd)
    {
        MinRam = paramMinRam; 
        MinDisk = paramMinDisk;
        CPUSpeed = paramCpuSpeedd;
        Name = paramName;
        Ram = paramMinRam;
        Disk = paramMinDisk;
    }
    public string Name{ get; set;}
    public decimal Ram { get; set; }
    public decimal Disk { get; set; }
    public decimal MinRam { get; set; }
    public decimal MinDisk { get; set; }
    public decimal CPUSpeed { get; set; }
    public void UpdateModel(decimal paramRam, decimal paramDisk, decimal paramCPUSpace)
    {
        Ram += paramRam;
        Disk += paramDisk;
        CPUSpeed += paramCPUSpace;
        this.NotifyObservers();
    }
    public void AddObserver(Windows98View paramView)
    {
        aList.Add(paramView);
    }
    public void RemoveObserver(Windows98View paramView)
    {
        aList.Remove(paramView);
    }
    public void NotifyObservers()
    {
        foreach (Windows98View view in aList)
        {
            view.Update(this);
        }
    }
}

Description: Here constructor is used to initialize the Model. UpdateModel() methods update the Model and is called by Controller. AddObserver() and RemoveObserver() method is used to add View with Model as an observer and delete observer from Model respectively. The NotifyObservers () method is used to loop through Observer list and notify all of them. Here only one Observer is used.

4. Create a User Control with name Windows98View.ascx.

The html part of View is shown below.

<%@ Control Language="C#" AutoEventWireup=true CodeBehind=Windows98View.ascx.cs
 Inherits=MVCForWinForms.Views.Windows98View %>
<div style="height: 30px; background-color: rgb(0, 148, 255); color: white; margin-bottom: 10px;">
    <asp:label style="display: block;" 
      text="Windows 98 System Configuration" runat="server" id="label1" />
</div>
<span style="float: left; font-weight: bold; color: rgb(0, 148, 255);">Current Status:&nbsp;</span>
<span>Ram:</span><asp:label runat="server" id="lblRam" /><span>GB</span>
<span>Disk:</span><asp:label runat="server" id="lblDisk" /><span>GB</span>
<span>CPU Speed:</span><asp:label runat="server" id="lblcpuspeed" /><span>GHz</span>
<table style="padding: 10px 0px; float: left; width: 365px;">
    <tbody><tr>
        <td style="font-weight: bold;">RAM:</td>
        <td><asp:textbox runat="server" id="txtRam" /></td>
        <td>GB</td>
    </tr>
    <tr>
        <td style="font-weight: bold;">Disk Space:</td>
        <td><asp:textbox runat="server" id="txtDisk" /></td>
        <td>GB</td>
    </tr>
    <tr>
        <td style="font-weight: bold;">Processor:</td>
        <td><asp:textbox runat="server" id="txtProcessor" /></td>
        <td>GHz</td>
    </tr>
    <tr>
        <td>
            <asp:button onclick="btnUpdate_Click" 
              text="Update" runat="server" id="btnUpdate">
        </asp:button></td>
        <td></td>
        <td></td>
    </tr>
</tbody>
</table>

The Code behind Part of View is shown below.

public partial class Windows98View : System.Web.UI.UserControl
{
    private Window98Controller Control;
    private Window98Model Model = new Window98Model("Windows 98", 2, 10, 2);
    protected void Page_Load(object sender, EventArgs e)
    {
        Control = new Window98Controller(Model,this);
        Model.AddObserver(this);
        Control.InitializedConponent(IsPostBack);
    }
    public decimal Ram { get; set; }
    public decimal Disk { get; set; }
    public decimal CPUSpeed { get; set; }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        CPUSpeed = Convert.ToDecimal(txtProcessor.Text.ToString());
        Ram = Convert.ToDecimal(txtRam.Text.ToString());
        Disk = Convert.ToDecimal(txtDisk.Text.ToString());
        Control.RequestUpdate(this);
    }
    public void Update(Window98Model paramModel)
    {
        UpdateInterface(paramModel);
    }
    public void UpdateInterface(Window98Model auto)
    {
        if (Ram != auto.Ram)
        {
            lblRam.Text = auto.Ram.ToString("n2");
        }
        if (Disk != auto.Disk)
        {
            lblDisk.Text = auto.Disk.ToString("n2");
        }
        if (CPUSpeed != auto.CPUSpeed)
        {
            lblcpuspeed.Text = auto.CPUSpeed.ToString("n2");           
        }
    }
    public void InitializedView(Window98Model paramModel)
    {
        lblRam.Text = paramModel.Ram.ToString("n2");
        lblDisk.Text = paramModel.Disk.ToString("n2");
        lblcpuspeed.Text = paramModel.CPUSpeed.ToString("n2");
    }
}

Description: Here one Model object is created with initial values and passed it to its Controller class, and called its AddObserver() method to bind the View as an observer.

Note: Here no relational database is used. Model is initialized by passing data to its constructor and the View is initialized using that data.

5. And finally create a page SystemCheck.aspx in which the User Control will run. The HTML part of the Page is shown below.

<%@ Page Language="C#" AutoEventWireup="true" 
     CodeBehind="SystemCheck.aspx.cs" Inherits="MVCForWinForms.SystemCheck" %>
<%@ Register Src="~/Views/Windows98View.ascx" TagPrefix="uc3" TagName="Windows98" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        body {
            font-family:Verdana;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div style="border:1px solid; width:500px; height:500px; margin:auto auto;">
        <uc3:Windows98 runat="server" id="Windows98" />
    </div>
    </form>
</body>
</html>

Conclusion

This example includes coupling between the View, Model and Controller. To reuse the Model and for Unit testing we should reduce the coupling and dependency on View. In the next tutorial I shall describe, how we can reduce the coupling and can reuse the Model for other Operating System Configuration, and Unit Testing.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here