Introduction

This article is used to demonstrate the MVC Pattern in .NET using C#/WinForm.

Here a simple "User Information Manager" application which is organized according the
the Model-View-Controller(MVC) pattern.

The application displays a list of contacts and allows you to add, modify, and delete
existing contacts. The idea is to separate the user interface into View (creates
the display, calling the Model as necessary to get information) and Controller
(responds to user requests, interacting with both the View and Controller as necessary).
The main advantage of MVC pattern is Loose Coupling. All the layers are separated
with their own functionality. It is easy to replace a layer with some other type
of layer. In other words, MVC pattern is to break up UI behavior into separate pieces
in order to increase reuse possibilities and testability. I am using Visual Studio
2010 Ultimate with .NET 4.0 for creating this Application.

Background

Model-View-Controller as the name applies considers three pieces:

Model: it should be responsible for the data of the application domain

View: it presents the display of the model in the user interface

Controller: it is really the heart of the MVC, the intermediary that ties the Model and the View together, i.e. it takes user input, manipulates the model & causes the view to update

The Solution

The User Information Manager is an application where you can store your customers' contact
information. The application displays a list of contacts and
allows you to add, modify, and delete existing contacts. All customers have an ID, first
name, last name and sex. The screen that operator of this app uses to maintain his list
of customers could look something like this:

List of customers can be viewed, added, removed and updated (currently is contains only V.I.P Members,
but if you want to become a member of the club, just ask " src="http://www.codeproject.com/script/Forums/Images/smiley_smile.gif" /> .... and no problems, it's free).
After a new user is added, his ID cannot change anymore.

The Class Diagram

In the design of a system, a number of classes are identified and grouped together in a class diagram which helps to determine the relations between objects.

The Description of Components

Part of Controller

In order to detach logic from the View, we have to make a View feel as helpless as possible, so we'd prefer to make the Controller do all the hard work and just hand the View some simple commands that do not require any further processing.
According to our design, we do this by defining an interface, IUsersView, which the View must implement.
This interface contain only the signatures of properties/methods we need to use.

Now we have a fairly good interface with number of methods.
Even if the MVC pattern formally declares that the Controller should receive the events and act upon the View, is often more practical and easier to have the View subscribe to the events and then delegate the handling to the Controller.

Finally I show the actual realization of the Controller (see the UsersController class). He hooks up the Model (User class) with View (UserView class).

The controller class is very important and central to the application. It's really important to keep it light, agile and loosely coupled to other components of the program.

Part of View

This section will focus on the scenario of loading the View with the list of users.
As said before our View must implement the IUsersView interface. A subset of the implementation is shown in the following code :

The SetController() member function of UsersView allows us to tell the View to which Controller instance it must forward the events and all event handlers simply call the corresponding "event" method on the Controller. As you can see here, UsersView also depends on abstractions...

Part of Model

This User class is a Model class. In this example, the User is an extremely simple domain class with no behavior, whereas in a realworld Domain Model you would probably have much more functionality in the domain classes.
The model is independent of the user interface. It doesn't know if it's being used from a text-based, graphical or web interface.
The Model only holds the in-memory state in a structured format. As you can see, the class contains only private data members and the public interfaces (properties) available to the client code

Why is it good?

The main advantage of using the MVC pattern is that it makes the code of the user interface more testable

It makes a very structured approach onto the process of designing the user interface, which in itself contributes to writing clean, testable code, that will be easy to maintain and extend

The Model-View-Controller is a well-proven design pattern
to solve the problem of separating data (model) and user interface (view)
concerns, so that changes to the user interface do not affect the data handling,
and that the data can be changed without impacting/changing the UI. The MVC
solves this problem by decoupling data access and business logic layer from UI
and user interaction, by introducing an intermediate component: the controller.
This MVC architecture enables the creation of reusable components within a
flexible program design (components can be easily modified)

Share

About the Author

Mr.Volynsky Alex is a Software Engineer in a leading software company. Alex is skilled in many areas of computer science. He has over 13 years of experience in the design & development of applications using C/C++/STL, Qt, MFC, COM/ActiveX, DirectShow, JavaScript, VBScript, Bash and of course - C#/.NET.

Alex is also interested in the Objective-C development for the iPad/iPhone platforms and he is the developer of the free 15-puzzle game on the App Store.

Overall, Alex is very easy to work with. He adapts to new systems and technology while performing complete problem definition research.

His hobbies include yacht racing, photography and reading in multiple genres.
He is also fascinated by attending computer meetings in general, loves traveling, and also takes pleasure in exercising and relaxing with friends.

It is about Visual Studio 2012 Compatibility...
In the past, whenever a new version of Visual Studio launches, developers needed to upgrade the project to new version of Visual Studio which was a pain, especially when you are working with a team of developers. Once a solution is upgraded to a newer version, it was not possible to going back. With Visual Studio 2012, you can avoid the pain of upgrading.
I created my project with VC2010 , but I think the VS2012 can convert projects when you first open them, but the changes are backward compatible with VS2012!
Please see here: http://msdn.microsoft.com/en-us/library/hh266747%28VS.110%29.aspx

The designer is equivalent to the View.
The code-behind is equivalent to the Controller as it can extract GUI values from the View and deliver them to the Model and it can push data from the Model to the View.
Since it has all the control objects you can set their properties with the Model easily, and update the Model with user input easily.

Furthermore in WinForms you have View inheritance which not only gives you an easy way to "not repeat yourself" but also makes it easy to use the same View with a different code-behind. which is like using a different ViewModel for the same View.

My opinion - this is WAY WAY better than WPF + MVVM where you need to really write a lot of complex code in order to pass objects from the view to the ViewModel and back, also the relationship between the View and the ViewModel is tighter than people are willing to admit.

If you changed your view, you're probably gonna need to change your ViewModel, e.g Command now receives an additional parameter from the view. Something pretty horrible here is that if you changed your View without updating your ViewModel, everything will compile just fine and you'll only get the exception at Runtime.

WPF is the future of GUI in .NET though and offers more advanced capabilities than WinForms did but in terms of language design I think WinForms was designed to be a lot more programmer-friendly

Notice, I'm not comparing the two technologies (WinfForms and WPF) here!
It has already been done before and on this site :Advantages and disadvantages of WPF over winforms ?
I have done a lot of winform projects, and have written a few WPF projects.
Yes, WPF is extremely powerful. I think it's one of the best technologies to come out of Microsoft. Still, however, making the decision between WPF and WinForms is a different story....

"WPF is the future of GUI in .NET...." It depends on what you mean....
Let's face it, some companies choose to stay the course with building on WinForms. Because it is easier and faster! The WPF is more complex...(There is a learning curve, the stuff, takes awhile to learn) Many people, and many companies both large and small have been using WinForms for years, and the technology has proven itself time and time again.

So, regarding applications written in WinForms : I think it's safe to assume that WinForms will still be supported for quite a long time...

I wanted to focus solely on how to implement the MVC pattern in WinForm! This article describes how to avoid ending up in Spaghetti Hell during your next WinForm project. WinForms in a certain sense encourages you to mix up business logic, data persistence and presentation.
Notice, this article only describes MVC pattern for WindowsForms applications , not for ASP, WPF and etc.

Of course I agree with you! The MVVM pattern is a powerful and useful alternative to MVC when designing a WPF application. WPF provides a rich environment for creating applications and encourages you to go using the MVVM approach. The MVVM pattern is similar to MVC (I'd describe it as a sibling of MVC)

Please forgive me if I'm being ignorant (again) but this seems to be actually MVP. MVC typically calls the controller directly, which in turn returns the appropriate view. Hence, MVC is better suited for the web (url's) and MVP works great with WinForms.

Great article either way. I have committed the sin of calling MVP MVC in a current proj for consistent naming with a third party framework.

I think even though you have stated that this is personal opinion, if you are going to go to the effort of advising against an approach taken in an article then you should at the very least provide some more illuminating information than that it 'goes against the nature of WinForms'.

One of the complexities of WinForms and in fact any platform that deals with user input is the approach taken to synchronise an in-memory state representation with a set of user interface components that each have their own state. This state management is complex by its nature - attempts such as those described in this article are not flawed due to a particular pattern. I disagree that MVC is not applicable to WinForms - as the author has shown you *can* create a logical entity that represents the controller, an abstraction of the view and a model, and bind them in the way that represents MVC.

Whether this is a good approach for all situations would need more investigation, and some of the mechanics of winforms, such as the fact that getting or setting a property on a UI element involves messages on the message pump and is therefore bound to the UI thread may affect things, but it is an interesting idea to try and apply a more rigorous approach to this sort of code than the usual mish-mash of event handers and spaghettified functions in form code.

@Alex- I'd be interested to see how much you could genericise this approach - for example, I'm sure that the UsersController could be separate into a SetOfEntitiesController or something like this - where an entity simply needs to be able to provide an ID. I'm sure with some templating and a few very lean interfaces the approach you've worked on could be applied to other UIs and enforced contractually by the compiler.

Anyway, interesting article - nice to see structure in the sometimes messy world of WinForms UI code!

I agree that maybe you shouldn't use Win Forms for MVC. I'm relatively new to MVC and I was taught to use the Templates in VS. I used 2010 VS Ultimate since you are using that as well. What I did not realize is that you must have used Win Forms which I have never seen anyone use with MVC. I see that your code runs OK but I built my project with MVC 4 with 2 projects. You have 4 projects. The one thing I just hate about Code Project is many of the Developers assume new people understand what they are doing but we don't. I have been trying to build many of the most popular projects but most of them don't work, probably because the tutorials are not specific enough for new developers to understand. Or the programs are built with old technology. When I go to school, we only work with the new technology and my instructor tells me never to learn old technology. He says go forward, not back. I am wasting a lot of time trying to get this program to run without errors but so far I'm having little success. I see now also I may have to add a view with HTML5 to get the same UI you have. Frustrating!

I think you have confusion over terms. You mean development for WEB, isn't it?

ASP.NET MVC 4 is a framework for building scalable, standards-based WEB (!!!) applications using well-established design patterns and the power of ASP.NET and the .NET Framework.

Windows Forms (WinForms) is the name given to the graphical application programming interface (API) included as a part of Microsoft .NET Framework, providing access to native Microsoft Windows interface elements by wrapping the extant Windows API in managed code. With Windows Forms you develop graphically rich applications .... Windows Forms has rich UI controls that emulate features in high-end applications like Microsoft Office. When you use the ToolStrip and MenuStrip control, you can create toolbars and menus that contain text and images, display submenus, and host other controls such as text boxes and combo boxes.
With the Visual Studio drag-and-drop Windows Forms Designer, you can easily create Windows Forms applications.

Thanks for the explanation. My instructor had told us that one of the knocks against ASP.NET MVC 4 is that you can't use the designer like you can in WinForms. We always code the Views by hand coding the HTML5 and using Razor.

When you begin developing applications with a user interface, you can use either Windows Forms or Web Forms. Both have full design-time support within the development environment, and can provide a rich user interface and advanced application functionality to solve business problems. Because of this feature parity, you might find it difficult to decide which technology is appropriate for a given application.
Certain application considerations might make the choice obvious. For example, if you are creating an e-commerce Web site that will be accessible to the public over the Internet, you would develop the application using Web Forms pages. If you are building a processing-intensive, highly responsive application that needs the full functionality of the client computer—such as an office productivity application—you would use Windows Forms.

Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages.
Server-based code can create dynamic web content on the fly, while a web page is written to the browser. When a web page is called, the server executes the server-based code inside the page before it returns the page to the browser. By running on the server, the code can perform complex tasks, like accessing databases.
Razor is based on ASP.NET, and designed for creating web applications. It has the power of traditional ASP.NET markup...

I wanted to know
1)If you data source changes in the view\Form how will you inform to the model that DataSource is changed and need to load new data from other data source.
2)do you know if there is any existing framework that has all DI inbuild to support data source switches based on some event.

Thank you tasumisra for your kind words and your evaluation of my work!

As I wrote earlier, to detach logic from the View, we have to make a View feel as helpless as possible, so our Controller should to do all the hard work ...
Therefore a View is in charge of presenting the data and processing user inputs. The View is only tightly coupled to the Controller,but a Controller communicates with both (View & Model)

Suppose I have form , I need to pass the values of form to controller. How could I do this? Can I create the object of class in Modle, fill that object and send to controller in order to take the save action..