Friday, April 8, 2011

MVC Architecture Model In ASP.NET

When developing ASP.NET applications the need of reducing code duplication increases along with their complexity. This is because testing and performing changes become very difficult tasks when having many different sources of code with the same functionality.

Model View Controller architecture (or pattern) allows us to separate different parts of our applications into tiers to fulfill this need.

MVC Overview

Model View Controller architecture aims to separate an application into three parts:
Model: It is the business logic of an application. From an object oriented perspective it would consist of a set of classes that implement the critical functionality of an application from a business point of view.
View: It can consist of every type of interface given to the user. In ASP.NET the view is the set of web pages presented by a web application.
Controller: This part of the architecture is the most difficult to explain, hence the most difficult to implement in many platforms. The controller is the object that allows the manipulation of the view. Usually many applications implement Model-Controller tiers that contain the business logic along with the necessary code to manipulate a user interface. In an ASP.NET application the controller is implicitly represented by the code-behind or the server side code that generates the HTML presented to the user.

Implementing MVC in ASP.NET

A basic diagram that would help us understand perfectly the specific parts that implement the Model View Controller architecture in an ASP.NET application is presented below:
MVC implementation in ASP.NET

MVC Model Implementation

When implementing the business logic of an application it is a must to use a Class Library project in order to generate a .dll file that will encapsulate all the functionality. This is critical as we as professional developers would not like to jeopardize the source code of a software product by placing the actual .cs files as a reference in a web application.
This type of project can be easily created in Visual Studio 2005 under the Visual C# or Visual Basic tabs:
Creating a Class Library Project
As a tutorial example we will develop a simple calculator under a new namespace we will call "Math".
Once the project is created we will add a class called Calculator:
Adding Calculator class
As the code is very simple and a sample is provided in this tutorial we will not get into much detail as far as how it is developed. The only important thing we need to mention is the way errors have to be handled in this class. Take a look at the following code:
1. protected float Divide(float fNumber1, float fNumber2)
2. {
3.   if (fNumber2 == 0)
4.  {
5.           throw new Exception"Second number cannot be equal to zero.");
6.    }
7.   return (fNumber1 / fNumber2);
8. }

When implementing the Divide function we need to ensure that the user would not be able to set the "fNumber2" parameter (line 1) to zero as a division between zero does not exist. The validation statement in lines 3-6 takes care of this case but the important fact we need to notice is that this class will NEVER use specific methods to present errors like message boxes or writing into labels. Errors captured in the model part of the architecture ALWAYS have to be presented in the form of exceptions (line 5). This will allow us to use this object in several types of applications like ASP.NET applications, Windows applications, Web services, etc.
Once we have finished coding our Calculator class the project has to be built in order to get the .dll file we will use in our Web application.

MVC View-Controller Implementation

The View and the Controller objects will be implemented by using a common ASP.NET Website. Once we have created our project we need to add the reference to the .dll file we created before.
The option to do this can be found in the context menu when right-clicking the project in the solution explorer:
Adding the a reference
We can find the file in the path "\bin\Release" (or "\bin\Debug" depending on how you build your class library) inside our main folder containing the math class library project:
Adding Math.dll reference
Once we have referenced our library we will create a simple web page that will allow us to choose between the four basic arithmetic operations and type two different numbers to operate.
The web page will look like this:
Calculator Web page
In the code behind we need to reference the Math namespace in order to use our Calculator class. The following statement will do that:
using Math;
As the code for this application is also simple we will only explain the method called when the "Operate!" button is clicked:
1. protected void btnOperate_Click(object sender, EventArgs e)
2. {
3.   if (pbValidateNumbers())
4.   {
5.        Calculator cOperator = new Calculator();
6.         try
7.         {
8.               txtResult.Text = cOperator.Operate(float.Parse(txtNumber1.Text.Trim()),float.Parse(txtNumber2.Text.Trim()), Convert.ToInt16(rblOperations.SelectedValue)).ToString();
9.               lbError.Text = "";
10.        }
11.        catch (Exception ex)
12.        {
13.              txtResult.Text = "";
14.              lbError.Text = ex.Message;
15.        }
16.  }
In line 3 we call the bool function "pbValidateNumbers" that will return true if the numbers typed in both textboxes are valid. These types of validations have to be performed by the controller object as they allow the interface to work properly and have nothing to do with the business logic.
In line 5 we create an instance of our Calculator class so we can perform the arithmetic operation. We call the method "Operate" (line 8) and return the value in another textbox. An important thing to mention is that we have to use a try-catch statement (lines 6-15) to handle any exception that could be thrown by our method "Operate" as every error caught in our Calculator class is handled by throwing a "digested" exception that is readable to the user.
In the code above we can appreciate how well encapsulated the business logic is, hence it can be reused in several applications without having to code it again.

Advantages of using MVC in ASP.NET

See full details:


laxminarayana said...

thank you

john son said...

Thanks for your wonderful post.It is really very helpful for us and I have gathered some important information from this blog.If anyone wants to get Dot Net Course in Chennai reach FITA, rated as No.1 Dot Net Training Institutes in Chennai.

sarah taylor said...

Thanks for your informative article and the blog. Your article is very useful for .net professionals and freshers looking for interview. Best DOT NET Training | Dot Net course Chennai

Naviya Nair said...

Very good article.. Nice Explanation..
ASP.Net MVC Training
Online MVC Training
Online MVC Training from India
MVC Training in Chennai

C# Training
Dot Net Training in Chennai
Dot Net Training institutes in Chennai
ASP.NET Training

Giri Mani 2 said...

This blog explain a detail about the model view controller architecture. Thank you very much for this blog. This is really helpful for dotnet users. The main and important thing is Model View Controller. Thanks for this blog.
Dotnet Training in Chennai

Bay Max said...

Nice explanation.Thanks a lot.
DOT NET Course Chennai
| DOT NET Training Institutes in Chennai

geethu said...

Excellent post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
Hadoop Training Chennai | PHP Training in Chennai

Sumaya Manzoor said...

It was very encouraging to see this kind of content. Thank you for sharing.
Salesforce Training in Chennai
Salesforce Training

Mouni yoga said...

Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
Click here:
angularjs training in btm
Click here:
angularjs training in rajajinagar

john jersy said...

Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.
Click here:
Microsoft azure training in tambaram
Click here:
Microsoft azure training in chennai

ummayasri said...

Excellent post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
Blueprism training in Chennai

Blueprism training in Bangalore

Blueprism training in Pune

Blueprism online training

Blueprism training in tambaram

ragul ragul said...

The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
Devops training in sholinganallur

devipriya chitra said...

Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.

best rpa training in chennai |
rpa training in chennai |
rpa training in bangalore
rpa training in pune | rpa online training

geetha sridhar said...

Pleasant Tips..Thanks for Sharing….We keep up hands on approach at work and in the workplace, keeping our business pragmatic, which recommends we can help you with your tree clearing and pruning in an invaluable and fit way.
Data Science course in kalyan nagar | Data Science course in OMR
Data Science course in chennai | Data science course in velachery
Data science course in jaya nagar | Data science training in tambaram

hansika hans said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
java training in chennai | java training in bangalore

java online training | java training in pune

Anonymous said...

I am so proud of you and your efforts and work make me realize that anything can be done with patience and sincerity. Well I am here to say that your work has inspired me without a doubt.

angularjs Training in chennai
angularjs Training in chennai

angularjs-Training in tambaram

angularjs-Training in sholinganallur

angularjs-Training in velachery

gowthunan said...

It’s always so sweet and also full of a lot of fun for me personally and my office colleagues to search you blog a minimum of thrice in a week to see the new guidance you have got.
safety course in chennai

shri yadav said...

I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
python course in pune
python course in chennai
python Training in Bangalore

afiah ahamed said...

Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
Java training in Pune

Java interview questions and answers

Java training in Chennai | Java training institute in Chennai | Java course in Chennai

Java training in Bangalore | Java training institute in Bangalore | Java course in Bangalore

sheela said...

It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command
Best Devops training in sholinganallur
Devops training in velachery
Devops training in annanagar
Devops training in tambaram

dhanya sridhar said...

I am sure this post has helped me save many hours of browsing other related posts just to find what I was looking for. Many thanks!
Data Science Training in Chennai
Data Science training in kalyan nagar
Data science training in Bangalore
Data Science training in marathahalli
Data Science interview questions and answers
Data science training in jaya nagar

gowthunan said...

And indeed, I’m just always astounded concerning the remarkable things served by you. Some four facts on this page are undeniably the most effective I’ve had.
iosh safety course in chennai

sheela rajesh said...

The article you presented here is really nice and there is no words to explain how you wrote this.
Thank you and add more data in future.
iOS Training in Chennai
Big Data Training in Chennai
Hadoop Training in Chennai
Android Training in Chennai
Selenium Training in Chennai
Digital Marketing Training in Chennai
JAVA Training in Chennai
German Classes in chennai
German language training in chennai
German classes in Tnagar

menaka13 said...

This post is really excellent with awesome stuff. Great content with useful information. Appreciate your effort, keep working. .Net Training in Bangalore

pavithra dass said...

Good job! Fruitful article. I like this very much. It is very useful for my research. It shows your interest in this topic very well. I hope you will post some more information about the software. Please keep sharing!!
German Classes in Chennai
German Language Classes in Chennai
Angularjs Training in Chennai
Selenium Training in Chennai
Software Testing Training in Chennai
German classes in Anna Nagar
German classes in Velachery

Shanthi Cabs said...

Amazing article. Your blog helped me to improve myself in many ways thanks for sharing this kind of wonderful informative blogs in live. I have bookmarked more article from this website. Such a nice blog you are providing ! Kindly Visit Us @ Tours and Travels in Madurai | Best Travels in Madurai | Madurai Travels

sasirekatamilselvan said...

Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.
angularjs online training

apache spark online training

informatica mdm online training

devops online training

aws online training

rose said...

Thank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me
Microsoft Azure online training
Selenium online training
Java online training
Python online training
uipath online training

Raji said...

Learned a lot from your blog. Good creation and hats off to the creativity of your mind. Share more like this.
Devops training in Chennai | Devops training Institute in Chennai

karthick said...

Thanks for sharing this information, it helps me to learn new things. Continue sharing more like this.
Best Data Science Training in chennai

cynthiawilliams said...

Excellent post. I learned a lot from this blog and I suggest my friends to visit your blog to learn new concept about technology.
Blue Prism Training in Chennai
Blue Prism Training Chennai
RPA Training in Chennai
Robotics Process Automation Training in Chennai
Machine Learning Training in Chennai
Data Science Course in Chennai
RPA Training in Anna Nagar
Blue Prism Training in Chennai
Blue Prism Training Chennai

Kayal m said...

This is the best blog and I was very impressed to me. I like this post and I learn a lot of knowledge on this topic. I am waiting for the next posts...
Corporate Training in Chennai
Corporate Training institute in Chennai
Spark Training in Chennai
Oracle Training in Chennai
Unix Training in Chennai
Power BI Training in Chennai
Oracle DBA Training in Chennai
Corporate Training in Chennai
Corporate Training institute in Chennai

Priyanka said...

Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
python training in bangalore