In this article, we will try to understand how an MVC application structure looks like, the application components and its functionality with a static and a dynamic output example.
Introduction
In this
article, we will try to understand how an MVC application structure looks like,
the application components and its functionality with a static and a dynamic
output example.
MVC
Overview:
The ASP.NET MVC framework is an
application pattern that provides an alternative to the ASP.NET Web forms for
creating web applications. A basic
introduction to ASP.NET MVC and its features were discussed in the first
article - http://www.dotnetfunda.com/articles/article2092-introduction-to-aspnet-mvc-csharp-part-1.aspx.
Typically,
the MVC design pattern can be illustrated with the following diagram.

Some kind of
web application can fetch the use of MVC framework, others can continue with
the traditional ASP.NET application pattern with posts backs and web forms.
Components:
MVC
Framework includes the following components:
· Model: Model is the application part,
which includes all the business logic. Model objects are responsible for
retrieving data from the database, operate on it and store its state back into
database. In some cases like Get Methods, where we just display the dataset the
same as in database and no physical existence of Model layer is required then
indirectly dataset plays the role of Model layer.
· View: Views are the components that
are responsible to display application’s User Interface. The business logic
after operated at Model, data returned from it is rendered on the UI based on
the User Interaction. View is all made of pure html and java script code. It is
highly time taking to design some of the asp controls like Calendar, charts,
etc., using HTML. Hence, HTML helper classes as well as plug in controls that
are available can be implemented.
· Controllers: Controllers are the
components that work as our Code behind part i.e., “.aspx.cs” of our “.aspx” in
Web Forms.
They handle the incoming requests i.e., user interaction, takes the input
from View, work with the Model and can select a view to render the data from
Model that displays as UI. Like how we will be handling the query string values
in the code behind part .aspx.cs file, the controllers would be helpful for
carrying the data to Model while user interaction.
Important Links:
Microsoft has released the MVC framework as open source. It can be
downloaded, inspected, modified, etc, You can get the MVC framework source code
from http://aspnet.codeplex.com. There are other a few components to be considered
while using the source code like IIS Express, SQL Server 2008 Management
Express studio, etc,
Essential Software: Web platform installer (WebPI) is a free tool
provided by Microsoft that downloads and installs components and products
required for the M/s Web platform. With Visual Studio 2010, you will get the
MVC 2 but don’t worry you can upgrade from it from here: http://microsoft.com/web/downloads. Click on download link. The WebPI
will start automatically and you can see a selection window “Products Category”
to select the products and click Install.

Start with our First Application:
Crete a new ASP.NET MVC Project – Select New Project from File menu and
click on New Project. By selecting the Web templates, you can see ASP.NET MVC3
Web Application as shown below:

Give a name and click on OK.
Now, you can see another dialog box, where you can choose among three
different types of MVC Project types.
· Empty
· Internet Application
· Intranet Application
Empty project includes all the required minimum folders and
files. Internet application gives you a sample web application which you can
edit and build it. Intranet application is also similar to internet application
but it is designed for use in environments that authenticate users through a
domain/Active Directory structure.

You can find a drop down “View Engine” in the above fig. MVC3
includes a new and improvised View Engine called RAZOR. We will discuss about the view engines later on. I recommend
you to select Razor View Engine. You can check or uncheck the HTML5 semantic
mark up which includes HTML5 intellisence. Now click OK. Now an empty project
is created, if you run it you can see a 404 error page since no URL request was
made.

This is the folder structure of our ASP.NET MVC application:

Let’s start with a high level easy application. Using Web
Mail helper to send email- a Feedback Form.
Adding a Controller:
Controllers are the simple C# classes inherited from System.Web.MVC.Controller – It is the controller base class. Each
public method that we write in the controller is called “Action Method”. The action
method can be invoked from the web page via a URL to perform corresponding
action.
Following
the naming conventions, the names that we give to a controller should end with
Controller like HomeController.

The
scaffolding options allows us to create a controller with template using common
functions. For now, we select Empty Controller and click Add. Now, you can see
HomeController.cs file in the Controller folder with a few lines code
indicating that Controller is part of MVC i.e., System.Web.MVC namespace on the
top and a class HomeController inheriting the Controller base class. Lets write
an action method named Index() which returns a string.
Public
string Index()
{
return “Hi, this is my First MVC
program”;
}
Note:
ASP.NET
applications also use the ASP.NET routing system, which decides how URL’s
should be mapped to corresponding action methods and controllers. Whenever we
create a MVC project, visual studio by default creates some routes following
its conventions, it sets the start of the application to HomeController’s Index
Method. Hence, following the naming conventions would be benefitting us.
However, we can change these default routing configuration in the Global.asax
page. Whenever a browser request http://yoursitename/ or http://yoursitename/Home
or http://yoursitename/Home/Index, it directs to the home controller’s
index action method itself.
Now, build
and run the above project. You can see
Hi, this is my First MVC program as output on the browser.

Now,
Controller does its part to render the string but not HTML. Therefore, it’s
time to set a UI to display our data. To produce a HTML response to the
browser, we need a View (UI).
Adding a
View :
Before we
directly add a view to a controller, first let us do few modifications. The
return type from the Index method was string now. Irrespective of the returning
data’s data type we should set the generic object form. This we call it as “ViewResult” and return View(); ie., we are instructing the MVC that the current
action method is going to call the default view() method [no parameter] and
return ViewResult.
HomeController
class:
public
ViewResult Index() {
return View();
}
Now, if we
run our application the MVC framework will be trying to search the default
view. But we didn’t add any view till now. Hence, it displays an error as shown
below. Good that, MVC framework also shows what it was expecting and where it
has search for:

This is due
to an exception raised indicating that no Index view or its master was found. To
create a view, you can right click in the HomeController.cs file, on the action
method name or within method body and add view.

The View
name will be same as action method name. If you are creating this view under
any master page keep the Use a layout or master page checkbox checked otherwise
uncheck it. For now, uncheck it as we are not implementing any master pages. If
you observe view folder, a view Index.cshtml file is now created under the
Views/Home folder.
Note: The
.cshtml extension indicated that it’s a C# View and will processed by Razor. In
previously versions of MVC, the views have .aspx extension since they are
relied on ASPX View engine.
The .cshtml
file has almost html part except the block
@{
Layout = null;
}
The above
code block will interpreted by the Razor View Engine. It just tells that we did
not include any master page. Let’s look forward and Include some html part
Index.cshtml
@{
Layout =
null;
}
<!DOCTYPE
html>
<html>
<head>
<title> Index </title>
</head>
<body>
<div>
Hi, I am from the Index View
</div>
</body>
</html>
The output
on the browser:

The
execution starts at the action method Index() of HomeController.cs file. Previously
this was returning a string, now it returns a ViewResult(), return View() will
execute to select a view. Here, we did not specify which view to be selected,
but based on the naming convention we followed it goes to the view with the
same name of action method. Hence index view is rendered.
Now, if we
look on to the Dynamic output application:
Like we
select a server control of aspx page and assign a value to it from the
codebehind. The same architecture we follow here, where aspx page is View and
Codebehind part is Controller. But, there is no connection between them. We
establish a way to pass data from controller to view using objects like ViewBag.
we modify
our Controller as:
HomeController.cs
:
public
ViewResult Index() {
int hour = DateTime.Now.Hour,
string Wish = hour < 12 ? “Good
Morning” : “Good Afternoon”;
ViewBag.Greeting = Wish;
return View();
}
ViewBag is a
dynamic object to which you can assign arbitrary properties, making those
values available in whatever view is subsequently rendered. The ViewBag’s
property can be given any name eg: Greeting here. This Greeting can be used to
retrieve data value in the ViewBag.
Index.cshtml
@{
Layout =
null;
}
<!DOCTYPE
html>
<html>
<head>
<title> Index </title>
</head>
<body>
<div>
@ViewBag.Greeting, world (from the view) </div>
</body>
</html>
The output
on the browser:

The data
binding expressions that we write in <%# %> syntax are replaced with @ in
MVC. @ is a syntax element of Razor engine, that is
used in ASP.NET MVC 3. We can just start @ and add out C# code within it. It is
more readable and we don’t need to worry about balancing <% %> tags.
Conclusion
I hope this article is
helpful. In the current
application, we did not yse Model. Let’s see more on Model, Action Result class
creating a sample application in the next article.
Reference