Blue Theme Orange Theme Green Theme Red Theme
 
Ads by Lake Quincy Media
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
World Class ASP.NET Hosting – Click Here for 3 Months Free/NO Setup Fee!
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET MVC & JQuery » Implementing MVC Design Pattern in .NET

Implementing MVC Design Pattern in .NET

This article explains the basic concept of the Model View Controller (MVC) design pattern and also shows how how closely .NET Framework can be used to implement the MVC design pattern with the one that originally conceived.

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


Introduction

Design patterns are very useful to solve complex design problems if used properly. This article explains the basic concept of the Model View Controller (MVC) Design pattern and also shows how closely .NET Framework can be used to implement the MVC design pattern with the one that originally conceived.

Prerequisites

Object Oriented-programming concepts, .NET Framework, ADO.NET, C#, XSD.

Definition/Description: Model View Controller (MVC)

View renders the data from the Model in response to the request made to the model by controlled events made by user interaction.

Model View Controller is a design approach to separate the application object model from GUI, originally invented around 80s. Then later on it has become a widely accepted common design pattern. The main objective behind this pattern is to decouple the view of the data (presentation layer) from the actual data processing so that the same model can be used for various views. This is achieved by using three different types of objects that interact with each other in loosely coupled manner with their discreet set of tasks.

These three objects are known as Model, View and Controller. We will learn for each of them here.

MVCDes1.gif

VIEW:

View is the graphical data presentation (outputting) irrespective of the real data processing. View is the responsible for look and feel, some custom formatting, sorting etc. View is completely isolated from actual complex data operations. For example, Online product catalog view is completely separated from database connection, query, tables etc. It simply gets final row-data from the model and puts some cosmetics and formatting before displaying it in browser. View provides interface to interact with the system. The beauty of MVC approach is that it supports any kind of view, which is challenging in todays distributed and multi-platform environment. 

A MVC model can have multiple views, which are controlled by controller. View interface can be of WEB-FORMS, HTML, XML/XSLT, XTML, and WML or can be Windows forms etc. 

MODEL:

Model is responsible for actual data processing, like database connection, querying database, implementing business rules etc. It feeds data to the view without worrying about the actual formatting and look and feel. Data provided by Model is display-neutral so it can be interfaced with as many views without code redundancy; this eases your code maintenance and reduces bugs and allows code -reuse at good extent. Model responds to the request made by controllers and notifies the registered views to update their display with new data.

CONTROLLER:

Controller is responsible for Notice of action. Controller responds to the mouse or keyboard input to command model and view to change. Controllers are associated with views. User interaction triggers the events to change the model, which in turn calls some methods of model to update its state to notify other registered views to refresh their display.

Benefits:

Following are the few of the benefits of MVC design pattern.

  • Since MVC handles the multiple views using the same enterprise model it is easier to maintain, test and upgrade the multiple system.

  • It will be easier to add new clients just by adding their views and controllers.

  • Since the Model is completely decoupled from view it allows lot of flexibilities to design and implement the model considering reusability and modularity. This model also can be extended for further distributed application.

  • It is possible to have development process in parallel for model, view and controller.

  • This makes the application extensible and scalable.

Drawbacks:

  • Requires high skilled experienced professionals who can identify the requirements in depth at the front before actual design. 

  • It requires the significant amount of time to analyze and design.

  • This design approach is not suitable for smaller applications. It Overkills the small applications.

.NET and MVC:

Lets try to find out how closely ASP.NET allows architecting application to meet MVC concept. 

Model: Dataset/Business Entities, DataAccess components
View: .ASPX pages

Controller: Code-behind .vb/.cs files

Typed dataset is one of the greatest features in .NET, which holds the application data in memory and represents the application business entity model, which bridges the UI components with Service Interface and Data Access layer.

So, service interface and Data Access components populate these typed Datasets. Now, these filled datasets can be bound to any view in UI layer.

.ASPX and ASCX pages server as view and mean to interface with application, while the code behind classes for these files server as the controller functions.

ASP.NET doesnt have central controller function, instead the code-behind file can directly make request to the Model and can update the dataset. But lot of controller function can be implemented in code behind class events in .aspx or .ascx pages, like Page_Onload(), OnItem_Created() etcevents.

.NET Framework has all Object-oriented features like code reuse, encapsulation etcSo, proper design of your model can make your user interface and view completely separated from model which can server multiple views. 

Sample Code:

The following sample illustrates the MVC design using .NET Framework with C#. This application retrieves the Orders from the database (we used XML File as data source) in typed dataset. This example has two different kinds of views for displaying orders on webform for the same Model using Web.UI controls. 

Code walkthrough:

Typed DataSet (Business Entity): 

This is the XML order xml schema, which represents the typed dataset for Orders.

MVCDes2.jpg

ASPX:

MVCDesign.aspx webform displays two different views for the same dataset.

protected MVCDesignCSharp.XMLData.Orders ordersDataSet;
private
void Button1_Click(object sender, System.EventArgs e)
{
BizOrderManager.GetOrderList(ordersDataSet);
if(DataGrid1.Visible==false)
{
DataList1.Visible =
false;
DataGrid1.Visible =
true;
DataGrid1.DataBind();
Button1.Text="Show View 1";
}
else
{
DataList1.Visible =
true;
DataGrid1.Visible =
false;
DataList1.DataBind();
Button1.Text="Show View 2";
}
}
private void Button2_Click(object sender, System.EventArgs e)
{
BizOrderManager.GetOrderList(ordersDataSet);
DataList1.Visible =
true;
DataGrid1.Visible =
true;
DataList1.DataBind();
DataGrid1.DataBind();
Button1.Text="Show Only View 2";
}

Business Objects:

This is the component method, which can be requested by controller. This business component can interact other data access components.

public static void GetOrderList(DataSet OrderDS)
{
OrderDS.ReadXml(AppDomain.CurrentDomain.BaseDirectory + "/XMLData/Orders.xml");
}

DataSource:

For easy configuration and simplification I have used XML files as data source for this application.

How to Run this Code:

  • Unzip the MVCDesign.zip

  • Build the solution MCDesign.sln

  • Run the application.


Login to add your contents and source code to this article
 About the author
 
nimesh panchal
Currently working as an independent consultant in New York City. Overall 5+ Years of experience in Software development having expertise in C#/VB.NET/ASP.NET /VB/JAVA/C++ and SQL Server/Oracle database 1.5 Years of experience in Microsoft .NET Technology. Main areas of expertise also includes analysis and designing application architecture using Design patterns, use cases, class model diagrams, database diagram, work flow for business functionalities and other software engineering concepts and models. 4+Years of solid industrial experience working with Microsoft technology for n-Tier E-Commerce and Client-server applications. Good hands on development tools like VisualStudio.NET, Visio, SQL Server, Oracle, Microsoft Project and many other tools.
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:
MVCDesignCSharp.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Good Article by Pushkar On February 12, 2007
Thanks a Lot man. Now i m little bit confident about MVC.
Reply | Email | Delete | Modify | 
MCV study by Nakul On February 19, 2007
The article is good and much closed to the concept. But The example do not serve the need to explain the same at practicle level
Reply | Email | Delete | Modify | 
ok by Bob On May 21, 2007
Nimesh wrote For easy configuration and simplification I have used XML files as data source for this application. You can't really skip over this part. For the article to be really useful, you need to include the database part. If you've used MVC with a real database, it shouldn't be too hard. You're off to a good start though.
Reply | Email | Delete | Modify | 
code behind makes for a lousy controller by Elmo On June 12, 2007
I've seen several examples of asp.net explaining how the code behind classes will serve as the control in an MVC pattern but I think this is wrong and will quickly cause an app to degenerate into one that is difficult to maintain and extend. The problem with the code behind is that it is very tightly coupled to the asp page itself meaning that you use the code behind classes as your controller, you then cannot reuse them for other, non-asp page based views. Moreover, classes that are tightly coupled to asp pages are very difficult to test which should be one of the goals of the MVC pattern. A better way is to create a completely separate controller class and have the code behind class marshall all of its events out to that class.
Reply | Email | Delete | Modify | 
code behind makes for a lousy controller by akhil On February 22, 2008
I too agree with you.Do you have a better solution to avoid this problem?
Reply | Email | Delete | Modify | 
code behind makes for a lousy controller by Elmo On June 12, 2007
I've seen several examples of asp.net explaining how the code behind classes will serve as the control in an MVC pattern but I think this is wrong and will quickly cause an app to degenerate into one that is difficult to maintain and extend. The problem with the code behind is that it is very tightly coupled to the asp page itself meaning that you use the code behind classes as your controller, you then cannot reuse them for other, non-asp page based views. Moreover, classes that are tightly coupled to asp pages are very difficult to test which should be one of the goals of the MVC pattern. A better way is to create a completely separate controller class and have the code behind class marshall all of its events out to that class.
Reply | Email | Delete | Modify | 
Re: code behind makes for a lousy controller by Ryan On July 11, 2007
Are you then saying the code behind should contain the model, or are you suggesting one should break the controller into two separate pieces?
Reply | Email | Delete | Modify | 
code to implement MVC not working by sara On July 27, 2007
I am working in VisualStudios 2005 and the code provided above is not opening,it says it needs a convertor. I am looking for simple model veiw controller code so as to acess the data on to the web forms. If any one has it please post as soon as possible .I am badly in need of it Thanks
Reply | Email | Delete | Modify | 
MVC by Sekar On August 28, 2007
ASP.NET is not a true MVC tool
Reply | Email | Delete | Modify | 
Re: MVC by girish On September 14, 2007

 

Yes, even MS does not claim ASPX as a true MVC. They would like it to be called as MVP (Model View Presenter). Actually view & controller are tightly coupled in ASPX. This violates the original concept of MVC preached & shipped by JAVA/STRUTS world. But MS answer is that in most of the deployment scenarios the controller happens to be tied to a framework/technology and cannot be generic enough. Mean to say that a controller written for web application cannot be used in another client server application context. Also they claim that writing generic controller would lead to the introduction of more layers in the request processing and could be a real killer in some situations.

 

 

 

 

Reply | Email | Delete | Modify | 
jMVC.NET by Codeville On November 6, 2007
That is certainly true. ASP.NET MVC is coming, but for now, you can implement your own MVC pattern or use a 3rd-party library. I've been involved in building an open-source *client-side* MVC library in which your .NET objects are transparently mapped to the Javascript world, then displayed through a simple templating system. When the user edits the objects, the UI is dynamically updated (including adding new controls etc.) without the need for AJAX or postbacks, and ultimately when the form is submitted, the updated .NET objects are available on the server. If this appeals to you, check out the demos linked from my blog: http://blog.codeville.net/2007/10/18/jmvcnet-neat-client-side-mvc-for-aspnet/
Reply | Email | Delete | Modify | 
MVC Architecture by Amritha On December 27, 2007
Great work... You are a true technologist... -- Amritha
Reply | Email | Delete | Modify | 
very helpful by Neeraj On February 1, 2008
very helpful
Reply | Email | Delete | Modify | 
great by Murali On February 13, 2008
Great Job
Reply | Email | Delete | Modify | 
Excellent Article by shiv On October 27, 2008
This is the best article for mvc,Thanks buddy
Reply | Email | Delete | Modify | 
hi by pavani On May 4, 2009
mvc
Reply | Email | Delete | Modify | 
request by kiran On November 11, 2009
nice to see..

Please provide us all design patterns which are supported .net and which are the regular use and suggestble
Reply | Email | Delete | Modify | 
Thanks for the explanation and sample application. by mani On November 14, 2009
Nice work!
Reply | Email | Delete | Modify | 
Good Article...Thanx by teamcoherent On January 20, 2010
Thanx Panchal its really goood article .....i got what i want in ur article.....
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.