Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET MVC & JQuery » Implementing the Passive View -- a Derivative of the Model-View-Control

Implementing the Passive View -- a Derivative of the Model-View-Control

This article demonstrates an implementation of the "Passive View Pattern" (based on the "Model View Control Pattern") for windows user controls.

Author Rank:
Total page views :  25863
Total downloads :  878
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
MVC_PassiveViewSample.zip
 
Become a Sponsor


Introduction.

A while ago I wrote an article about the MVC pattern and just recently received a request for an example closer to a real-world implementation so I thought I would share the approach I have used in live projects.

There are a bunch flavors of MVC.  Here is an article by Martin Fowler about some of the differences if you really want to dig in. For this article, we'll be discussing building a passive view to keep the model and the view as "dumb"  as possible and avoid any dependencies between two.  The idea being that all of our implementation should lie in the control and not in the UI (the view).

So let's get started....

Part I. A Control Base Class

Since we'll be coding many different types of controllers for different views and models, it makes sense to pull the common functionality out into a base class and have the supertypes handle the parts that are different.  Using this technique we come up with what is called the "template pattern" for all you design pattern junkies out there.  The controller will need to keep references to both the view and the model and we'll be using an event driven architecture to wire things up.  What will happen, is the control will listen to events from the view and the model and be responsible for updating the view if the model changes and updating the model with change requests from the view.

 image002.gif 

 A control will need references to both the view and the model and will also need a bunch of event handlers for notifications received from both the view and the model.  With our control base class, we don't know what the specific events will be to wire up from the concrete implementations of the view and model, so we'll create a few abstract methods as placeholders.  We'll eventually need to connect the three pieces (the model, view and control).  We'll do this using an Initialize() method that will be responsible for wiring all the connections between the control and it's model and view.  Just to keep things clean, we'll make this class disposable in order to unwire all the events if the object is explicitly disposed to avoid any unexpected behavior.

public abstract class MvcControlBase<TModel, TView> : IDisposable
{
    #region Member Variables

    protected TView m_view;
    protected TModel m_model;

    #endregion

    #region Abstract Methods

    protected abstract void WireEvents();
    protected abstract void UnwireEvents();
    protected abstract void SetViewState();

    #endregion

    #region Methods

    public virtual void Initialize(TModel model, TView view)
    {
        if (m_model != null || m_view != null)
            UnwireEvents();

        m_model = model;
        m_view = view;

        SetViewState();
        WireEvents();
    }

    #endregion

    #region Properties

    public TModel Model { get { return m_model; } }
    public TView View { get { return m_view; } }

    #endregion

    #region IDisposable Members

    public void Dispose()
    {
        UnwireEvents();
    }

    #endregion
}

Part II. The Control-View Wiring.

We need an object to carry the message from the view to the control when the view is requesting a change to a property of the model.  In order to do this, we'll be using a custom class derived from EventArgs that will carry the new value that has been requested by the view.

    public class PropertyChangeRequestEventArgs<T>:EventArgs
    {
        public PropertyChangeRequestEventArgs(T pRequestedValue)
        {
            RequestedValue = pRequestedValue;
        }

        public T RequestedValue { get; set; }
    }

Because we'll have a separate event for each property the view is expressing on the UI, we'll build a helper class to keep track of all the events in one handy object.  This is a bit tricky to do while keeping everything type safe because different properties have different types. The signature for this pool is below and the code is attached to his article and uses a similiar technique to the Generic Identity Map I wrote about in a previous article in order to consolidate objects of different types. 
 image004.jpg

So now that we are done laying our foundations, let's look at constructing our MVC.

Part III. MVC Implementation

The Model

First, let's look at a simple model.  Let's say we have a "cat" object with "name" and "age" properties.  We want to be able to notify the control of any changes to these properties.  Luckily, these events are already built into the framework in the "System.ComponentModel" namespace. If you haven't dug into this namespace, it has a lot to offer in terms of building an event driven architecture. We'll use the pattern exposed by the INotifyPropertyChanged interface which dictates that we have one event (PropertyChangedEventHandler) that our model can use to expose property changes that our controller can listen to.    

public class CatModel: INotifyPropertyChanged
{

    #region Member Variables

    private String m_name;
    private Int32 m_age;
    private event PropertyChangedEventHandler m_propertyChanged;

    #endregion

    #region Properties

    public String Name
    {
        get { return m_name; }
        set
        {
            if(m_name != value)
            {
                m_name = value;

                // if there is a change... raise the event to notify the control
                if(null != m_propertyChanged)
                    m_propertyChanged(this, new PropertyChangedEventArgs("Name"));
            }
        }
    }

    public Int32 Age
    {
        get { return m_age; }
        set
        {
            if (m_age != value)
            {
                m_age = value;

                // if there is a change... raise the event to notify the control
                if (null != m_propertyChanged)
                    m_propertyChanged(this, new PropertyChangedEventArgs("Age"));
            }
        }
    }

    #endregion

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged
    {
        add{ m_propertyChanged += value; }
        remove{ m_propertyChanged -= value; }
    }

    #endregion
}

The Abstract View

Next, let's look at our view.  We'll be creating our view as an interface, so we are not tied to any one concrete view.    This way, any UI user component implementing our interface can be controlled by a controller.  The controller needs to be able to set the name and age in the view as well as register and un-register for change request events that the view will fire.

    public interface ICatView
    {
        String CatName { set; }
        Int32 CatAge { set; }
        void RegisterChangRequestListener<T>(String propertyName, EventHandler<PropertyChangeRequestEventArgs<T>> handler);
        void UnRegisterChangRequestListener<T>(String propertyName, EventHandler<PropertyChangeRequestEventArgs<T>> handler);
    }

The Controller

Finally, our controller class will be responsible for managing both the view and model.  All we have to do is implement our abstract MvcControlBase<CatModel, ICatView> class by building event handlers, wiring up the events, and making sure everything is initialized by calling Initialize() in the constructor.

public class CatControl: MvcControlBase<CatModel, ICatView>
{
    public CatControl(CatModel model, ICatView view)
    {
        Initialize(model, view);
    }

    protected override void WireEvents()
    {
        Model.PropertyChanged += Model_PropertyChanged;
        View.RegisterChangRequestListener<String>("Name", View_OnNameChangeRequest);
        View.RegisterChangRequestListener<Int32>("Age", View_OnAgeChangeRequest);
    }

    protected override void UnwireEvents()
    {
        Model.PropertyChanged -= Model_PropertyChanged;
        View.UnRegisterChangRequestListener<String>("Name", View_OnNameChangeRequest);
        View.UnRegisterChangRequestListener<Int32>("Age", View_OnAgeChangeRequest);
    }

    private void View_OnNameChangeRequest(Object sender, PropertyChangeRequestEventArgs<String> args)
    {
        Model.Name = args.RequestedValue;
    }

    private void View_OnAgeChangeRequest(Object sender, PropertyChangeRequestEventArgs<Int32> args)
    {
        Model.Age = args.RequestedValue;
    }

    private void Model_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        switch (e.PropertyName)
        {
            case "Name":
                View.CatName = Model.Name;
                break;
            case "Age":
                View.CatAge = Model.Age;
                break;
            default:
                throw new ArgumentException("Property not handled: " + e.PropertyName);
        }
    }

    protected override void SetViewState()
    {
        View.CatAge = Model.Age;
        View.CatName = Model.Name;
    }
}

Of course, this is a very simplistic control where the control is doing nothing but handling the requests and updating the values in the view and model, but in the real world the control would probably have validation logic and/or business rules encapsulated as well.

Part IV. Concrete Views

We'll be building two windows "cat" views.  The first will display the name and age allow incrementing the age through a button.  The second will display the name in a textbox (so we can update it) and the age in a label.

 image006.jpg 

Both our views will use the ChangeRequestEvents that we briefly discussed earlier to hold an event pool for all the events the view can raise which makes wiring things up pretty easy.  As you can see from the code below, implementing the ICatView interface is pretty simple using the pool and just requires firing the appropriate event when we get event messages from the UI.

public partial class CatView1 : UserControl, ICatView
{
    #region Constructors

    public CatView1()
    {
        InitializeComponent();
        m_changeRequestedEvents = new ChangeRequestEvents(this);
    }

    #endregion

    #region Member Variables

    private ChangeRequestEvents m_changeRequestedEvents;

    #endregion

    #region Methods

    private void m_btnIncrementAge_Click(object sender, EventArgs e)
    {
        m_changeRequestedEvents.Fire<Int32>("Age", Int32.Parse(m_lblAge.Text) + 1);
    }

    #endregion

    #region ICatView Members

    public int CatAge
    {
        set
        {
            m_lblAge.Text = value.ToString();
        }
    }

    public string CatName
    {
        set { m_lblName.Text = value; }
    }

    public void RegisterChangRequestListener<T>(string propertyName, EventHandler<PropertyChangeRequestEventArgs<T>> handler)
    {
        m_changeRequestedEvents.RegisterListener<T>(propertyName, handler);
    }

    public void UnRegisterChangRequestListener<T>(string propertyName, EventHandler<PropertyChangeRequestEventArgs<T>> handler)
    {
        m_changeRequestedEvents.UnRegisterListener<T>(propertyName, handler);
    }

    #endregion
}

The code for the other view is very similar so I won't put it here, but it is in the code attached to this article.

Part IV. Implementing the Concrete Views

Now that we have the views in place, we will place them on a form and wire them up as follows.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        CatModel model = new CatModel() { Age = 10, Name = "Fluffy" };

        new CatControl(model, m_catView1); // wire up cat view 1
        new CatControl(model, m_catView2); // wire up cat view 2
    }
}

And that's it.  It might be a good idea to keep references to each control and explicitly dispose them when the form is disposed, but since this is the main form and process will close when the form closes, it wasn't crucial in this case.

Check out the project attached to this article and you'll notice that one of the cool things about using the MVC pattern is when the model is updated, ALL the view are updated because the model notifies all listening controls which then update their respective views.

 image008.gif

There are many different flavors of the MVC that we can use to build our applications I just happen to particularly like the Passive View for it's clean separation of each component of the MVC pattern.  If you are interested in using the MVC for web applications, it is definitely worth checking out the new MVC web  framework.

Until next time,

Happy coding


Login to add your contents and source code to this article
 About the author
 
Matthew Cochran
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
MVC_PassiveViewSample.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
VS2005 by Bob On February 1, 2008
Nice job Matthew. The VS2005 solution is posted here: http://rdn-consulting.com/blog/2008/02/01/selecting-a-mvcmvp-implementation-for-a-winforms-project/ Bob
Reply | Email | Delete | Modify | 
Re: VS2005 by Matthew On February 3, 2008
Thanks :)
Reply | Email | Delete | Modify | 
Implementing the Passive View by Jim On March 1, 2008
I thoroughly enjoyed your article! I have a few questions. If I understand correctly, business logic/rules are to be implemented in the controller? If you wanted to persist your model data where/how would you do that.? Would you create a separate data access assembly and make calls to that from the controller (I am assuming you want the model as dumb as possible, so it can't persist itself)? Jim
Reply | Email | Delete | Modify | 
Re: Implementing the Passive View by Matthew On March 4, 2008

I think I wasn't clear now that I look back at the article (sorry for any confusion). 

The "business rules" for displaying the data like validation would live in the control. 

The "business rules" for the domain (whatever you are modeling) would be in the model which is where your persistance layer would tie in.

You are right in thinking we probably don't want persistance in the domain logic code, and it would probably be best to seperate this out into another library that would act as a gateway between the db and the object model calling some factory methods we can expose in the model layer.  The model really has no business knowing how it is persisted because it is not really part of the model and we would not have a clear seperation of concerns if we dumped everything in one project.  At the very least, we should have the data gateway code in it's own namespace.

The short answer is that the controller just controls the display (and nothing else or it would get really confusing).

 

Reply | Email | Delete | Modify | 
Implmenting passive view by Alan On March 8, 2008
Thanks for a great article. I have used the combination of Fowler's Passive View and Supervising Controller in several applications and find your implementation with an abstract base class for the controller very helpful.
Reply | Email | Delete | Modify | 
Very good, but not completely dynamic? by kasper On April 2, 2009
One of the only implementations of MVC in winforms I have found and a very good too. However, I have some problems with passing the property names as strings, since changing them in the ICatView will not result in an error, but make the whole thing fail. Could it be implemented more dynamically, such that the property name inherits whatever is in the view interface?
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.