Anda di halaman 1dari 74



Software Designing Principles
Software Design Patterns represent strategies for applying Software Design Principles. In other words,
a Software Design Principle is a good idea and a Software Design Pattern is the tool that you use to
implement the good idea. The idea behind Software Design Patterns was originally promoted by the
book Design Patterns: Elements of Reusable Object-Oriented Software (This book is known as
the Gang of Four book). This book has inspired many other books that describe Software Design
Patterns. The Head First Design Pattern book provides a more user-friendly introduction to the
design patterns from the Gang of Four book. The Head First Design book devotes chapters to 14
patterns with names like Observer, Faade, Singleton and Adaptor.

Software Design Patterns provide you with patterns for making your code more resilient to change. For
example, in many places in this book, well be taking advantage of a Software Design Pattern named
the Repository Pattern. Eric Evans, in his book Domain-Driven Design, describes the Repository
pattern like this:

A REPOSITORY represents all objects of a certain type as a conceptual set (usually emulated). It acts
like a collection, except with more elaborate querying capability. Objects of the appropriate type are
added and removed, and the machinery behind the REPOSITORY inserts them or deletes them from
the database. According to Evans, one of the major benefits of the Repository pattern is that it enables
you to decouple application and domain design from persistence technology, multiple database
strategies, or even multiple data sources. (ibid) In other words, the Repository pattern enables you to
shield your application from changes in how you perform database access.
For example, when we write our forums application at the end of this book, well take advantage of the
Repository pattern in order to isolate our forums application from a particular persistence technology.
The forums application will be designed in such a way that we could switch between different data
access technologies such as LINQ to SQL, the Entity Framework, or even NHibernate.

Writing Unit Tests for Your Code

By taking advantage of Software Design Principles and Patterns, you can build software that is more
resilient to change. Software Design Patterns are architectural patterns. They focus on the gross
architecture of your application. If you want to make your applications more change proof on a more
granular level, then you can build unit tests for your application. A unit test enables you to verify
whether a particular method in your application works as you intend it to work.

There are many benefits that result from writing unit tests for your code:
1) Building tests for your code provides you with a safety net for change.
2) Building tests for your code forces you to write loosely coupled code.
3) Building tests for your code forces you to take a user perspective on the code.

First, unit tests provide you with a safety net for change.

Test Driven Development (TDD)

Test-driven development is a software design methodology that makes unit tests central to the
process of writing software applications. When you practice test-driven development, you write tests
first and then write code against the tests. More precisely, when practicing test-driven development,
there are three steps that you complete when creating code (Red/ Green/Refactor):

Write a unit test that fails (Red)

Write code that passes the unit test (Green)

Refactor your code (Refactor)

First, you write the unit test. The unit test should express your intention for how you expect your code
to behave. When you first create the unit test, the unit test should fail. The test should fail because
you have not yet written any application code that satisfies the test. Next, you write just enough code
in order for the unit test to pass. The goal is to write the code in the laziest, sloppiest and fastest
possible way. You should not waste time thinking about the architecture of your application. Instead,
you should focus on writing the minimal amount of code necessary to satisfy the intention expressed
by the unit test.

Finally, after you have written enough code, you can step back and consider the overall architecture of
your application. In this step, you rewrite (refactor) your code by taking advantage of software design
patterns such as the Repository pattern so that your code is more maintainable. You can
fearlessly rewrite your code in this step because your code is covered by unit tests.

What is ASP.NET MVC?

The Microsoft ASP.NET MVC framework is Microsofts newest framework for building web applications.
The ASP.NET MVC framework was created to support pattern-based software development. In other
words, the framework was designed to make it easier to implement software design principles and
patterns when building web applications. Furthermore, the ASP.NET MVC framework was designed to
its core to support unit tests. Web applications written with the ASP.NET MVC framework are highly

The fact that ASP.NET MVC applications are highly testable makes the ASP.NET MVC framework a great
framework to use when practicing test-driven development. Microsofts framework for building
software applications any type of application including desktop, web, and console applications is
called the .NET framework. The .NET framework consists of a vast set of classes, tens of thousands of
classes, which you can use when building any type of software application. For example, the .NET
framework includes classes for working with the file system, accessing a database, using regular
expressions, and generating images.

The ASP.NET framework is one part of the .NET framework. The ASP.NET framework is Microsofts
framework for building web applications. It contains a set of classes that were created specifically to
support building web applications. For example, the ASP.NET framework includes classes for
implementing web page caching, authentication, and authorization.

Microsoft has two frameworks for building web applications built on top of the ASP.NET framework:
ASP.NET Web Forms and ASP.NET MVC.


The ASP.NET MVC framework is new. However, the MVC software design pattern itself has a long
history. The MVC pattern was invented by Trygve Reenskaug while he was a visiting scientist at the

Smalltalk group at the famed Xerox Palo Alto Research Center. He wrote his first paper on MVC in
1978. He originally called it the Thing Model View Editor pattern, but he quickly changed the name of
the pattern to the Model View Controller pattern. The MVC pattern was first implemented as part of
the Smalltalk-80 class library. It was originally used as an architectural pattern for creating graphical
user interfaces (GUIs).

The meaning of MVC shifted radically when the pattern was adapted to work with web applications. In
the context of web applications, the MVC pattern is sometimes referred to as the Model 2 MVC
pattern. The MVC pattern has proven to be very successful. Today, the MVC pattern is used by several
popular web application frameworks including Ruby on Rails, Merb, and Django. The MVC pattern is
also popular in the Java world. In the Java world, MVC is used in the Struts, Spring, and Tapestry

The first major MVC framework for ASP.NET was the open source MonoRail project (see There continues to be an active developer community around this project.

The Microsoft ASP.NET MVC framework was originally created by Scott Guthrie on an airplane trip to
Austin, Texas to speak at the first Alt.NET conference in October, 2007 (Scott Guthrie was one of the
co-creators of ASP.NET). Scott Guthries talk generated so much excitement that the ASP.NET MVC
framework became an official Microsoft product. ASP.NET MVC 1.0 was released in the first part of

ASP.NET MVC 2 was released just one year later, in March 2010. Some of the main features in
MVC 2 included:

UI helpers with automatic scaffolding with customizable templates

Attribute-based Model validation on both client and server

Strongly-typed HTML helpers

Improved Visual Studio tooling

ASP.NET MVC 3 (generally abbreviated as MVC 3) shipped just 10 months after MVC 2, driven by the
release date for Web Matrix. If MVC 3 came in a box, it might say something like this on the front:

Expressive Views including the new Razor View Engine!

.NET 4 Data Annotation Support!

Streamlined validation with improved Model validation!

Powerful hooks with Dependency Resolution and Global Action Filters!

Rich JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding!

Now with NuGet

Architecture of an ASP.NET MVC Application

An MVC application, a Model View Controller application, is divided into the following three parts:

Model An MVC model contains all of an applications logic that is not contained in a View or
Controller. This includes all of an applications validation logic, business logic, and data access
logic. The MVC Model contains model classes which are used to model objects in the
applications domain.

View An MVC view contains HTML markup and view logic.

Controller An MVC controller contains control-flow logic. An MVC controller interacts with
MVC Models and Views to control the flow of application execution.

Enforcing this separation of concerns among Models, Views, and Controllers has proven to be a very
useful way of structuring a web application.

ASP.NET MVC is a Microsofts one more Web application framework designed with separation of
concerns and testability in mind. It is built on CLR and completely based on MVC architecture and so
we think in terms of controllers and Views. ASP.NET doesnt have support for ViewState and server
controls, so we get feel of old web here.

ASP.Net & ASP.Net MVC Differences

ASP.NET WebForms
Uses the Page Controller pattern. Each page
has a code-behind class that acts as a
controller and is responsible for rendering the
Uses an architecture that combines the
Controller (code behind) and the View
(.aspx). Thus the Controller has a dependency
on the View. Due to this, testing and
maintainability becomes an issue.
The View is called before the Controller.
At its core, you cannot test your controller
without instantiating a View. There are ways

Uses the Front Controller pattern. There is a single
central controller for all pages to process web
application requests and facilitates a rich routing
ASP.NET MVC enforces a "separation of concerns".
The Model does not know anything about the View.
The View does not know theres a Controller. This
makes MVC applications easier to test and maintain
Controller renders View based on actions as a result
of the User Interactions on the UI.
At its core, ASP.NET MVC was designed to make
test-driven development easier. You can test your

to get around it using tools.

WebForms manage state by using view state

and server-based controls.
WebForms supports an event-driven
programming style that is like Windows
applications and is abstracted from the user.
The State management is made transparent
by using sessions, viewstate etc. In the
process, the HTML output is not clean making
it difficult to manage later. The ViewState also
increases your page size.
Deep understanding of HTML, CSS and
JavaScript is not required to a large extent
since the WebForm model abstracts a lot of
these details and provides automatic
plumbing. While abstracting details to provide
ease of use, sometimes a solution is
overcomplicated, than it needs to be.
WebForms can drastically reduce time while
building up intranet and internet applications
that use a lot of controls (drag and drop
model). Although this is true for development,
a lot of time is spent later to code around
Relatively simple to learn and pickup. Works
very well for developers who initially have
trouble with the HTTP/HTML model and are
coming from a similar WinForms oriented
event model.
Lesser amount of code is required to build
webapps since a lot of components are
integrated and provided out of the box. You
can also use a lot of data controls provided
out of the box that rely on ViewState.
Works very well for small teams where focus
is on rapid application development

Controller without instantiating a View and carry

out unit-tests without having to run the controllers
in an ASP.NET process.
ASP.NET MVC does not maintain state information
by using view state
In ASP.NET MVC, the output is clean and you have
full control over the rendered HTML. The orientation
is towards building standard compliant pages and
provides full control over the behavior of an

A thorough understanding of how HTML, CSS and

JavaScript work together is required. The
advantage is you can do a lot of jQuery and AJAX
stuff in an efficient and simple manner than you
would do in an ASP.NET application.

You lose the 'drag and drop' quick model of building

your web applications. The focus is on control over
the application behavior and test-driven
development. The model is extensible and you do
not have to spend time working around limitations.
There is a learning curve to understand the why,
when and how of ASP.NET MVC.

Since the application tasks are separated into

different components, amount of code required is
more. Since ASP.NET MVC does not use ViewState,
you cannot use Data controls like GridView,
Works well for large projects where focus in on
testability and maintainability

Asp.Net MVC Advantages

Test driven Development - In MVC controller is a separate class so automatic testing is possible
featuring Test Driven Development. Controllers are not bound to any specific view and so can be
reused for multiple views.
Performance - ASP.NET MVC dont have support for view state, so there will not be any automatic
state management which reduces the page size and so gain the performance.
Full control over HTML - ASP.NET MVC doesnt support server controls, only option available is using
html input controls, so we will be sure about final html rendered at the end. We will also be aware
about 'id' of every element. And so integration of ASP.NET MVC application with third party JavaScript
libraries like jQuery becomes easy.

Support for parallel development - In ASP.NET MVC layers are loosely coupled with each other, so
one developer can work on Controller, at the same time other on View and third developer on Model.
This is called parallel development.
SEO, URL routing and REST - Rich routing features lets treat every URL as a resource supporting
RESTful interfaces.
Extensibility - ASP.NETMVC supports multiple view engines like aspx, razor and if required we can
create our own.
Existing ASP.NET Features ASP.NET MVC framework is built on top of matured ASP.NET
framework and thus provides developer to use many good features such as forms authentication,
windows authentication, caching, session and profile state management etc.

How it works



User makes the request for some resource in server (by putting some URL in the browser).
Request comes to controller first (routing engine is the one who is responsible for deciding
which request will be handled by which controller. In this article we wont talk in depth about
this behavior).
Controller if required talk to model for data.
Model operates on database (or on some other data sources) and return data (in form of
business objects) to controller.
Controller chooses the appropriate view (like say Customer view which will may contain some
html tables, drop downs, textboxes).
Controller passes the data (model data retrieved in step 4) to chosen view(in step 5), where
data will be populated as per convenience.
Controller sends back view to the user.

MVC 3 Installation
The developer tooling for ASP.NET MVC 3 supports Visual Studio 2010 or Visual Web Developer 2010
Express (free). You can install MVC 3 using the Web Platform Installer. When you install MVC 3 on a
server, the MVC runtime assemblies are installed in the Global Assembly Cache (GAC), meaning they
are available to any website running on that server. After installing MVC 3, youll have some new
options in Visual Studio 2010 and Visual Web Developer 2010. The experience in both IDEs is very
similar; because this is a Professional Series book well be focusing on Visual Studio development,
mentioning Visual Web Developer only when there are significant differences.

MVC Features

The Razor View Engine

Improved support for Validation
Rich JavaScript support
Support for output caching
Enhanced support for dependency injection

Razor View Engine: The Razor View Engine is a new View Engine introduced in ASP.NET MVC 3. You
can use this View Engine to write compact and expressive syntax to integrate server code into your
HTML markup code. To use the Razor View Engine for your ASP.NET MVC application, you need to
select the "ASP.NET MVC 3 Web Application (Razor)" project in Visual Studio 2010 under web
Validation Improvement: MVC 3s support for the .NET 4 IValidatableObject interface deserves
individual recognition. You can extend your model validation in just about any conceivable way by
implementing this interface on your model class and implementing the Validate method,
Rich JavaScript support: Unobtrusive JavaScript is a general term that conveys a general
philosophy, similar to the term REST (for Representational State Transfer). The high-level description
is that unobtrusive JavaScript doesnt affect your page markup. For example, rather than hooking in
via event attributes like onclick and onsubmit, the unobtrusive JavaScript attaches to elements by
their ID or class. MVC3 supports unobtrusive JavaScript in two ways like Ajax helpers and Ajax
Support for Output Caching: ASP.NET MVC 3 also includes another feature called Child Action
Output Caching. This allows you to cache only a portion of the response when you are using
Html.RenderAction or Html.Action. This cache can be varied by action name, action method signature
and action method parameter values.
Dependency Resolution: ASP.NET MVC 3 introduces a new concept called a dependency resolver,
which greatly simplifies the use of dependency injection in your applications. This makes it easier to
decouple application components, which makes them more configurable and easier to test.

Creating a new ASP.NET MVC 3 project

Well start by selecting New Project from the File menu in Visual Web Developer. This brings up the
New Project dialog.
Well select the Visual C# Web Templates group on the left, then choose the ASP.NET MVC 3 Web
Application template in the center column. Name your project and press the OK button.

This will display a secondary dialog which allows us to make some MVC specific settings for our
project. Select the following:
Project Template - select Internet Application
View Engine - select Razor
Use HTML5 semantic markup - unchecked
Verify that your settings are as shown below, then press the OK button.

This will create our project. Lets take a look at the folders that have been added to our application in
the Solution Explorer on the right side.

Understanding the MVC Application Structure

When you create a new ASP.NET MVC application with Visual Studio, it automatically adds several files
and directories to the project, as shown above. ASP.NET MVC projects by default have six top-level

Where you
Where you
Where you
Where you
Where you
Where you

put Controller classes that handle URL requests.
put classes that represent and manipulate data and business objects
put UI template files that are responsible for rendering output, such as
put JavaScript library files and scripts (.js)
put CSS and image files, and other non-dynamic/non-JavaScript
store data files you want to read/write

The /Controllers directory, youll find that Visual Studio added two Controller classes
HomeController and AccountController by default to the project.
The /Views directory, youll find that three subdirectories /Account, /Home, and /Shared as well
as several template files within them, were also added to the project by default.

The /Content and /Scripts directories, youll find a Site.css file that is used to style all HTML on the
site, as well as JavaScript libraries that can enable jQuery support within the application.

MVC and Conventions

ASP.NET MVC applications, by default, rely heavily on conventions. This allows developers to
avoid having to confi gure and specify things that can be inferred based on convention.
For instance, MVC uses a convention-based directory-naming structure when resolving View

and this convention allows you to omit the location path when referencing Views from within
a Controller class. By default, ASP.NET MVC looks for the View template file within the \Views\
[ControllerName]\ directory underneath the application.
MVC is designed around some sensible convention-based defaults that can be overridden as needed.
This concept is commonly referred to as convention over configuration.
ASP.NET MVCs conventions are pretty straightforward. This is what is expected of your applications

Each Controllers class name ends with Controller ProductController, HomeController, and so
on, and lives in the Controllers directory.

There is a single Views directory for all the Views of your application.

Views that Controllers use live in a subdirectory of the Views main directory and are named
according to the controller name (minus the Controller suffix). For example, the views for the
ProductController discussed earlier would live in /Views/Product. All reusable UI elements live
in a similar structure, but in a Shared directory in the Views folder.

We began with an introduction to ASP.NET MVC, showing how the ASP.NET web framework and the
MVC software pattern combine to provide a powerful system for building web applications. You looked
at how ASP.NET MVC has matured through two previous releases, looking in more depth at the
features and focus of ASP.NET MVC 3.

With the background established, you set up your development environment and began creating a
sample MVC 3 application. You fi nished up by looking at the structure and components of an MVC 3

** ** **

In this Chapter
In this chapter we will describe about how the Controller will respond the HTTP request. It focuses
more on Controller and Actions.

The Controller is responsible for controlling the ay that user interacts with MVC application.
Controllers within the MVC pattern are responsible for responding to user input, often making changes
to the model in response to user input. In this way, controllers in the MVC pattern are concerned with
the flow of the application, working with data coming in, and providing data going out to the relevant
The controller is a component that deals with the performance of any business-related tasks triggered
within the page. A controller is invoked in response to some user action and likely needs some input
data to do its job. The controller is a sort of mediator between the user interface and the application's
middle tier. The typical behavior of a controller can be summarized in four main steps:

Getting input data.

Executing the request-related action method.

Preparing data for the view.

Triggering the refresh of the view.

A controller exposes controller actions. An action is a method on a controller that gets called when you
enter a particular URL in your browser address bar. For example, imagine that you make a request for
the following URL:
In this case, the Index() method is called on the ProductController class. The Index() method is an
example of a controller action. There are below few points can be considered for Controller:

A controller action must be a public method of a controller class.

There are some additional requirements that must be satisfied by a controller action.

A method used as a controller action cannot be overloaded.

Furthermore, a controller action cannot be a static method.

All controllers in an MVC application implement the IController interface.

Controller sets the data to View to use.

If you wanted to write your application at this level, you could simply derive all your controllers from
the IController interface and provide an implementation of the Execute method. By default, the
controllers you add to an ASP.NET MVC project derive from the System.Web.Mvc.Controller class.
One way to add a new controller is to right-click on the Controllers folder in Solution Explorer and
select Add Controller, which gives you the dialog box.

If you select the Controller, it will show the Controller name as Default Controller.

Rename the DefaultController to your own like StudentController and click on Add button. Now you
can observe the StudentController.cs file in the Controllers folder in Solution Explorer.

Your new StudentController already has an Index method. This method (Index() method) within your
controller are called controller actions. Now we need to add the View for this Index method to display
the content.

To add a View to an action (method), right click on the Method and choose Add View option from
context menu.

It prompts the Add View dialog box for inputs. Give the View name and uncheck use a layout or
master page checkbox.

Click on Add button, it will adds a Student folder and Index. Cshtml file automatically in Views folder.

Now open the Index.cshtml file from Student folder and enter below code.

Layout = null;
<!DOCTYPE html>

<h3>Welcome to Student Controller</h3>

Now run the project and make request for Student controller using below url:

The Student Controller will return the Index() action (method) as default.
Now add another 2 actions inside the Student Controller and test the functionality. To do it, add the
below 2 action methods inside the Student Controller.

// GET: /Student/GetName
public string GetName()
return "My Name is Naresh";
// GET: /Student/GetCourse
public string GetCourse()
return "My Course is ASP.Net MVC";
Try to make request to the Student Controller and Actions like GetName and GetCourse. Here note
that we need not to add a View for these actions because these actions were returning the String
value which can be displayed directly on the browser windows.
Following the above steps of creating View add Views for the GetName() and GetCourse() methods.
Make request to the actions and see the response as below:

GetName() action result:

GetCourse() action result:

Parameters in Controller Actions

Along with call to the Action methods inside the Controller, it is possible to pass the Parameter values
to the action methods.
By default, the values for action method parameters are retrieved from the request's data collection.
The data collection includes name/values pairs for form data, query string values, and cookie values.
The controller class locates the action method and determines any parameter values for the action
method, based on the RouteData instance and based on the form data. If the parameter value cannot
be parsed, and if the type of the parameter is a reference type or a nullable value type, null is passed
as the parameter value. Otherwise, an exception is thrown.

For example write an Action method with a Parameter and try to call the action method using below
sample. Write the below action method inside the Student controller.

// GET: /Student/GetPhone/1234
public string GetPhone(string id)
string msg = "My Phone No.: " + id;
return msg;

Try to make a call to GetPhone() action method inside Student Controller by passing Id value. The
response will be as below:

For the above sample we are using Id as the parameter value which is mapped in the Global.asax file
RegisterRoutes() method. If you want to pass more than one Parameter to an action method, you
need to pass them as QueryString values.

.. ..
// GET: /Student/GetDetails/1234?name=abcd
public string GetDetails(string id, string name)
string msg = "My ID: " + id;
msg += " My Name: " + name;
return msg;
.. ..

Action Result Types

Most action methods return an instance of a class that derives from ActionResult. The ActionResult
class is the base for all action results. However, there are different action result types, depending on
the task that the action method is performing. For example, the most common action is to call the
View method. The View method returns an instance of the ViewResult class, which is derived from
The following table shows the built-in action result types and the action helper methods that return
Action Result

Helper Method




Renders a view as a Web page.

Renders a partial view, which defines a section of a
view that can be rendered inside another view.

Redirects to another action method by using its URL.



Redirects to another action method.



Returns a user-defined content type.



Returns a serialized JSON object.



Returns a script that can be executed on the client.



Returns binary output to write to the response.



Represents a return value that is used if the action

method must return a null result (void).
ActionResult: By default, the Controller actions will return the ActionResult object. We can return
various types of results as ActionResult, which will decide how the output needs to render on the


public ActionResult About()

return View();

When we need to return any text from a Controller action, we will use the Content type.

public class ActionsController : Controller
// GET: /Actions/
public ActionResult Index()

return View();

public ActionResult IndexContent()

return Content("Hello from Actions Controller");

.. ..

RedirectToAction: Depending on the input values, we can redirect to another Action. For redirecting
to another Action, we will use the RedirectToAction type. In below example, we will make a call to
Redirect2 action method but the controller will be passed to Redirect1 action method. It will work like
Response.Redirect() method in ASP.Net.

.. ..
public class ActionsController : Controller
// GET: /Actions/
public ActionResult Index()
return View();
public ActionResult IndexContent()
return Content("Hello from Actions Controller");

public ActionResult Redirect1()

return Content("I have got control from Redirect2 action..");
public ActionResult Redirect2()
// Redirect to Redirect1 action inside the Actions Controller
return RedirectToAction("Redirect1", "Actions");

.. ..

RedirectToRoute: When we need to redirect to a route defined in Global.asax, we will use the
RedirectToRoute object. We will learn route defining in Routing chapter.
File: File is used to return the content of a file to the browser. For our sample, I am returning the
web.config to the browser.
.. ..

.. ..

public ActionResult IndexFile()

return File("..\\Web.config", "text/html");

JSON: We can render the text to the result page or can send it as a file to the client using JSON

.. ..
public JsonResult IndexJson()

List<string> countries = new List<string>();

return Json(countries, JsonRequestBehavior.AllowGet);
.. ..

When we make request to an action method which returns the Json object, the Browser cannot
understand directly so we need to Save the content in the local drive and open by using Editor like

Action Filters
Action filters allow the developer to participate in the action and result execution pipeline in four ways:
for authorization, for pre- and post-processing of actions, for pre- and post-processing of results, and
for error handling. Action filters can be written as attributes that are applied directly to the action
methods (or controller classes), or as standalone classes that are registered in the global filter list. If
you intend to use your action filter as an attribute, it must derive from FilterAttribute.

Authorize filters ensure that the corresponding Action will be called by an authorized user only. If the
user is not authorized, he will be redirected to the login page.
The below is the example for Authorize filter. Add [Auhorize] attribute for About() action method
inside Home Controller.
.. ..

public class HomeController : Controller

public ActionResult Index()
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();


.. ..

public ActionResult About()

return View();

Now make request to About() action method and the controller should redirect the user to Login page
for authorization.

The ASP.NET MVC framework supports four different types of filters:


Authorization filters Implements the IAuthorizationFilter attribute.

Action filters Implements the IActionFilter attribute.
Result filters Implements the IResultFilter attribute.
Exception filters Implements the IExceptionFilter attribute.

Filters are executed in the order listed above. For example, authorization filters are always executed
before action filters and exception filters are always executed after every other type of filter.
Authorization filters are used to implement authentication and authorization for controller actions. For
example, the Authorize filter is an example of an Authorization filter.
Action filters contain logic that is executed before and after a controller action executes. You can use
an action filter, for instance, to modify the view data that a controller action returns.
Result filters contain logic that is executed before and after a view result is executed. For example,
you might want to modify a view result right before the view is rendered to the browser.
Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised
by either your controller actions or controller action results. You also can use exception filters to log

Base ActionFilterAttribute Class: In order to make it easier for you to implement a custom action
filter, the ASP.NET MVC framework includes a base ActionFilterAttribute class. This class implements
both the IActionFilter and IResultFilter interfaces and inherits from the Filter class.

The base ActionFilterAttribute class has the following methods that you can override:
OnActionExecuting This method is called before a controller action is executed.
OnActionExecuted This method is called after a controller action is executed.
OnResultExecuting This method is called before a controller action result is executed.
OnResultExecuted This method is called after a controller action result is executed.

Marking Public Methods as Non-Action Methods

By default, the MVC framework treats all public methods of a controller class as action methods. If
your controller class contains a public method and you do not want it to be an action method, you
must mark that method with the NonActionAttribute attribute.

private void DoSomething()
// Method logic.

Razor in Views
Microsoft has introduced a new view engine called Razor that replaces ASPX as the default view engine
in ASP.NET MVC3. Razor represents a major improvement for developers that want a cleaner and more
efficient view engine with fewer keystrokes. Razor also allows the developer full control of every
character sent to the browser including whether or not the ASP.NET JavaScript libraries are used at all.
Razor does away with ASP's <% %> block types and instead intelligently infers what is intended to be
server side code versus client side code. The at (@) symbol is used to denote a server side statement
and the double @@ is how you include a literal @ symbol on your page. This single character is used
to transition from markup to code and sometimes also to transition back.
There are two basic types of transitions: Code expressions and Code blocks.
Code Expressions: These are evaluated and written to the response. For example, in the following

<h1>Listing @stuff.Length items.</h1>

notice that the expression @stuff.length is evaluated as an implicit code expression and the result, 3,
is displayed in the output.

Implicit Code Expression: As described before, code expressions are evaluated and written to

the response. This is typically how you display a value in a view.

Web Forms

<span><%: model.Message %></span>

Explicit Code Expression: As described before, code expressions are evaluated and written to

the response. This is typically how you display a value in a view.

Web Forms

<span>NIT<%: nit %></span>

Unencoded Code Expression: In some cases, you need to explicitly render some value that

should not be HTML encoded. You can use the Html.Raw method to ensure that the value is not
Web Forms

<span><%: Html.Raw(model.Message) %></span>

<span><%= model.Message %></span>

Calling a Generic Method: This is really no different than an explicit code expression.
Web Forms
<%: Html.MyMethod () %>
Code Blocks: Razor also supports code blocks within a view. Going back to the sample view, you
may remember seeing a foreach statement:

@foreach(var item in stuff)

<li>The item name is @item.</li>
This block of code iterates over an array and displays a list item element for each item in the array.

The many advantages to of Razor View Engine are that it:

Is the default
Has clean lightweight syntax
Has layouts
Has HTML encoded by default
Has support for scripting with C#/VB
Has IntelliSense support in Visual Studio

Razor Layouts
Many of the core concepts of ASPX translate well to Razor including Layout pages which are Razor's
master pages equivalent. When you create a blank MVC3 application, the default layout template is
in /Views/Shared/_Layout.cshtml.
Layouts in Razor help maintain a consistent look and feel across multiple views within your application.
If youre familiar with Web Forms, layouts serve the same purpose as Master Pages, but offer both a
simpler syntax and greater flexibility. You can create additional layout pages and reference them at
the top of your individual Razor .cshtml views shown below.


Page.Title="Your Page Title";

Layout = "~/Views/Shared/MyCustomLayout.cshtml";

Inside the layout page itself, @RenderBody() defines where the page that uses your layout page will
render its content. You can optionally, also implement a reference to @Page.Title if you want your
layout page to have a proper HTML title. It is possible to define as many custom sections as needed in
your layout page using the @RenderSection function. If it is marked as required, the page will throw
an exception if the view utilizing the layout does not define the section.

@RenderSection("RazorIntroSection", required:true)
To define the custom section in your corresponding view page, use the @section function along with
your section name. All of the HTML and functions inside of the brackets will be a part of that subsection.

@section RazorIntroSection
<p>This is the razor intro section defined in my view.</p>

The Model in Razor

At the top of your Razor page, you can optionally define an @model type. Doing so isn't required but if
you define it, intellisense will work correctly across your page and compile time validation will be
performed accurately on your view. In the example below, if your view returns List<string>, you can
iterate that list as shown below with full intellisense support.

@model List<string>
Layout = "~/Views/Shared/_Layout.cshtml";
Page.Title = "Model Bound Page";
<p>This is my list:<p>
@foreach(string label in Model)

<tr><td>@label .ToUpper()</td></tr>

View Engine
Usually, this means that you will create a CSHTML file containing markup and script, and ASP.NET
MVCs default view engine implementation, the RazorViewEngine, will use some existing ASP.NET APIs
to render your page as HTML.
To better understand what a view engine is, lets review the ASP.NET MVC life cycle.

It is very important to note here that the Controller itself does not render the view; it simply prepares
the data (that is, the model) and decides which view to display by returning a ViewResult instance.

Configuring View Engine

View engines are configured in Global.asax.cs. By default, there is no need to register other view
engines if you stick with just using RazorViewEngine (and the WebFormViewEngine is also registered
by default). However, if you want to replace these view engines with another, you could use the
following code in your Application_Start method:

protected void Application_Start() {

ViewEngines.Engines.Add(new MyViewEngine());

What is View
The view is responsible for providing the user interface (UI) to the user. It is given a reference to the
model, and it transforms that model into a format ready to be presented to the user. Starting in
ASP.NET MVC 3, view data can also be accessed via the ViewBag property. ViewBag is a dynamic
property that provides a convenient syntax for accessing the same data accessible via the ViewData
property in MVC2.
For example, in Controller write below piece of code store value in ViewBag which can be access in
View page.

public class NITController : Controller

public ActionResult MyView()
ViewBag.Message = Hello World. Welcome to ASP.NET MVC!;
return View();


Layout = null;
<!DOCTYPE html>
<head><title>My View</title></head>

This is a sample view. Its not much to look at,
but it gets the job done.
When you create a new project template, youll notice that the project contains a Views directory
structured in a very specific manner. By convention, the Views directory contains a folder per
Controller, with the same name as the Controller, but without the Controller suffix. Thus for the
HomeController, theres a folder in the views directory named Home.

Add View Dialog Box Options

For example, you are writing a new Action Show inside a Controller, and want to create a View for
that Action; we will take support of Add View dialog box.

The Add View item will allow providing the View name, View engine etc. details.

View name: The name of the View file.

View Engine: The second option in the dialog is the view engine. Starting in ASP.NET MVC 3,
the Add View dialog supports multiple view engine options. By default, there are two options in the
dialog, Razor and ASPX.
Create a strongly-typed view: Selecting the checkbox labeled Create a Strongly-Typed View
enables typing in or selecting a model class. The list of types in the drop-down is populated using
reflection so make sure to compile the project at least once before specifying a model type.
Scaffold template: Once you select a type, you can also choose a scaffold template. These are T4
templates that will generate a view based on the model type selected.


Creates an empty view. Only the model type is specified using the
@model syntax.
Creates a view with a form for creating new instances of the model.
Generates a label and editor for each property of the model type.
Creates a view with a form for deleting existing instances of the model.
Displays a label and the current value for each property of the model.
Creates a view that displays a label and the value for each property of
the model type.
Creates a view with a form for editing existing instances of the model.
Generates a label and editor for each property of the model type.
Creates a view with a table of model instances. Generates a column for
each property of the model type. Make sure to pass an
IEnumerable<YourModelType> to this view from your action method. The
view also contains links to actions for
performing the create/edit/delete operations.

Reference Script Libraries: This option is used to indicate whether the view you are creating should
include references to a set of JavaScript files if it makes sense for the view. By default, the
_Layout.cshtml file references the main jQuery library, but doesnt reference the jQuery Validation
library nor the Unobtrusive jQuery Validation library.
When creating a view that will contain a data entry form, such as an Edit view or a Create view,
checking this option ensures that the generated view does reference these libraries. These libraries
are necessary for implementing client-side validation. In all other cases, this checkbox is completely
Create as a Partial View: Selecting this option indicates that the view you will create is not a full
view, thus the Layout option is disabled. For the Razor view engine, the resulting partial view looks
much like a regular view, except there wont be the <html> tag nor <head> tag at the top of the
Use a layout or Master Page: This option determines whether or not the view you are creating will
reference a layout (or master page) or will be a fully self-contained view. For Razor view engines,
pecifying a Layout is not necessary if you choose to use the default layout because the layout is
already specifi ed in the _ViewStart.cshtml fi le. However, this option can be used to override the
default Layout file.

Strongly Typed View

Strongly typed views are a really handy feature of the ASP.NET MVC framework. Aside from the
obvious advantage of binding form data to a particular class or view model, the ability to extend this
concept to templates/views with complex data types. The way it fundamentally works is based on
what you put in is what you get out.
If you have a use case where you wanted to bind this particular class to a form (to create a New
person), it would be pretty straight forward up until you got to the complex type.
Create the Model as below:

public class Person


public string fname {set; get;}

public int age {set; get;}
To assign a complex type to a template/view you simply utilise the html mvc helpers Html.ControlFor.
In this particular instance because you are not dealing with a simple html control like a text box you
would use below:

public ActionResult About()

var personModel = new Person();

return View(personModel);


@model MvcApplication.Models.Person
ViewBag.Title = "Details";
<h2>Person Details</h2>
<div class="display-label">Name</div>
<div class="display-field">
@Html.DisplayFor(model => model.fname)
<div class="display-label">Age</div>
<div class="display-field">
@Html.DisplayFor(model => model.age)

HTML Helpers
An HTML Helper is just a method that returns a string. The string can represent any type of content
that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML
<input> and <img> tags. You also can use HTML Helpers to render more complex content such as a
tab strip or an HTML table of database data.
The ASP.NET MVC framework includes the following set of standard HTML Helpers (this is not a
complete list):



Html.BeginForm: The version of BeginForm in the preceding code, with no parameters, sends an
HTTP POST to the current URL, so if the view is a response to /Person/Edit/52, the opening form tag
will look like the following:

<form action=/Person/Edit method=post>

An HTTP POST is the ideal verb for this scenario because you are modifying album information on the

@using (Html.BeginForm(Edit, Person, FormMethod.Post,

new {target = _blank}))
Html.ValidationSummary: The ValidationSummary helper displays an unordered list of all validation
errors in the ModelState dictionary. The Boolean parameter you are using (with a value of true) is
telling the helper to exclude property-level errors, however. In other words, you are telling the
summary to display only the errors in ModelState associated with the model itself, and exclude any
errors associated with a specific model property. We will be displaying property-level errors separately.
Assume you have the following code somewhere in the controller action rendering the edit view:

ModelState.AddModelError(, This value is wrong!);

ModelState.AddModelError(Title, Nice name!);
Html.Lable: To display the Label for a field input.

@using (Html.BeginForm())
@Html.ValidationSummary(excludePropertyErrors: true)
<legend>Edit Album</legend>
@Html.DropDownList(GenreId, ViewBag.Genres as SelectList)


@Html.TextBox(Title, Model.Title)

<input type=submit value=Save />


Html.TextBox (and Html.TextArea): The TextBox helper renders an input tag with the type
attribute set to text. You commonly use the TextBox helper to accept free-form input from a user.

@Html.TextBox(Title, Model.Title)
Use TextArea to render a <textarea> element for multi-line text entry.

@Html.TextArea(text, hello <br/> world)

Html.DropDownList (and Html.ListBox): Both the DropDownList and ListBox helpers return a
<select/> element. DropDownList allows single item selection, whereas ListBox allows for multiple
item selection.

public ActionResult Edit(int id)

var p = storeDB.Person.Single(a => a.Id== id);
ViewBag.Persons = new SelectList(p.Names);
return View();
.. ..
@Html.Label(Person ID)
@Html.DropDownList(PID, ViewBag.Persons as SelectList)
Html.ValidationMessage: When there is an error for a particular fi eld in the ModelState dictionary,
you can use the ValidationMessage helper to display that message.

public ActionResult Edit(int id, FormCollection collection)
var p = storeDB.Persons.Find(id);
ModelState.AddModelError(Title, name not found!);
return View();
In the view, you can display the error message with the following code:

@Html.ValidationMessage(Title, some wrong value)

Templated Helpers
The templated helpers in ASP.NET MVC build HTML using metadata and a template. The metadata
includes information about a model value (its name and type), as well as model metadata
(added through data annotations). The templated helpers are Html.Display and Html.Editor.
For example, the Html.TextBoxFor helper renders the following HTML for an albums Title

<input id=Title name=Title type=text

value= />
Instead of using Html.EditorFor, you can switch to using the following code:

@Html.EditorFor(m => m.Title)

The EditorFor helper will render the same HTML as TextBoxFor, however, you can change the
HTML using data annotations. If you think about the name of the helper (Editor), the name is
more generic than the TextBox helper (which implies a specifi c type of input). When using the
template helpers, you are asking the runtime to produce whatever editor it sees fit. Lets see
what happens if you add a DataType annotation to the Title property:

[Required(ErrorMessage = A Title is required)]

public string Title { get; set; }
Now the EditorFor helper renders the following HTML:

<textarea class=text-box multi-line id=Title name=Title>

Sample text
Html.Hidden: The Html.Hidden helper renders a hidden input. For example, the following code:

@Html.Hidden(wizardStep, 1)
results in:

<input id=wizardStep name=wizardStep type=hidden value=1 />

The strongly typed version of this helper is Html.HiddenFor. Assuming your model had a
WizardStep property, you would use it as follows:

@Html.HiddenFor(m => m.WizardStep)

Html.Password: The Html.Password helper renders a password fi eld. Its much like the TextBox
helper, except that it does not retain the posted value, and it uses a password mask. The
following code:


results in:

<input id=UserPassword name=UserPassword type=password value=/>

The strongly typed syntax for Html.Password, as youd expect, is Html.PasswordFor. Heres how
youd use it to display the UserPassword property:

@Html.PasswordFor(m => m.UserPassword)

Html.RadioButton: Radio buttons are generally grouped together to provide a range of
possible options for a single value.The Html.RadioButton helper renders a simple radio button:

@Html.RadioButton(color, red)
@Html.RadioButton(color, blue, true)
@Html.RadioButton(color, green)
Html.CheckBox: The CheckBox helper is unique because it renders two input elements. Take
the following code, for example:

This code produces the following HTML:

<input id=IsDiscounted name=IsDiscounted type=checkbox

value=true />

Html.ActionLink & Html.RouteLink: The ActionLink method renders a hyperlink (anchor tag)
to another controller action. Like the BeginForm helper you looked at earlier, the ActionLink
helper uses the routing API under the hood to generate the URL.
For example, when linking to an action in the same controller used to render the current view,
you can simply specify the action name:

@Html.ActionLink(Link Text, Person/Edit)

Custom Helpers

The ASP.NET MVC framework contains a small set of helpers. Most likely, you will need to extend
the MVC framework with custom HTML Helpers. The easiest way to create a new HTML Helper is
to create a static method that returns a string.
Imagine, for example, that you decide to create a new HTML Helper that renders an HTML
<label> tag. You can use the class in Listing 2 to render a<label>.

using System;
namespace MvcApplication1.Helpers
public class LabelHelper
public static string Label(string target, string text)
return String.Format("<label for='{0}'>{1}</label>", target, text);
In the View, use the LabelHelper to render HTML <label> tags. Notice that the view includes an
@using directive that imports the Helpers namespace.

@using HelperTest.Helpers;
ViewBag.Title = "Home Page";
To learn more about ASP.NET MVC visit <a href="" title="ASP.NET MVC
@using (Html.BeginForm())
@Html.Label("firstName", "First Name:")
<br />

<br /><br />
@Html.Label("lastName", "Last Name:")
<br />
<br /><br />
<input type="submit" value="Register" />


Partial Views
In addition to returning a view, an action method can also return a partial view in the form of a
PartialViewResult via the PartialView method.
Create an ASP.Net MVC application and add new view to View folder by checking the Create as a
Partial View checkbox.

Create a Model as partial.

.. .. ..
public partial

class MyPartial
int id

{ get;
name {

set; }
get; set; }
{ get; set; }
{ get; set; }

public partial class MyPartial

public List<MyPartial> lstPartialModel { get; set; }
.. .. ..
Create an Action inside HomeController using the partial model.

.. .. ..

private List<MyPartial> GetSampleData()

List<MyPartial> model = new List<MyPartial>();
model.Add(new MyPartial()
Id=1, Name= "A", Actual = 10000, Target = 12000 });
model.Add(new MyPartial()
Id=2, Name = "B", Actual = 8000, Target = 14000 });
model.Add(new MyPartial()
Id=3, Name = "C", Actual = 50000, Target = 35000 });

return model;

.. .. ..
In the HomeController, change the Index() action result with GetSampleData() return type.
.. .. ..

public ActionResult Index()


ViewBag.Message = "Welcome to ASP.NET MVC!";

//return View();
return View(new MyPartial() { lstPartialModel = GetSampleData() });

.. .. ..

In Index view, I have included partial view as given below.

@model IEnumerable<MyPartialView.Models.MyPartial>
@using MyPartialView.Models
ViewBag.Title = "MyData";

<div data-role="page" data-title="Partial View Test" data-add-back-btn="true" data-back-btntext="Back">
<div class="grid" style="margin-left: 5px;" id="grid">
@if (Model != null)
<div class="grid">
<table cellspacing="0" width="80%">
@foreach (var itm in Model)
<td align="center"> @itm.Id </td>
<td align="center"> @itm.Name </td>
<td align="center"> @itm.Actual </td>
<td align="center"> @itm.Target </td>
<br />

Now render the Partial View on a View page (similar to User Control).
@model MyPartialView.Models.MyPartial
ViewBag.Title = "Home Page";
To learn more about ASP.NET MVC visit <a href="" title="ASP.NET MVC

@Html.Partial("MyData", Model.lstPartialModel)
Run the application and you can see the Partial View result on Index page.




A Model is set of classes that describe the data youre working with as well as the business rules for
how the data can be changed and manipulated. These are the classes with C# or VB.Net that
represent the domain you are interested in. These domain objects often encapsulate data stored in a
database as well as code used to manipulate the data and enforce domain-specific business logic. With
ASP.NET MVC, this is most likely a Data Access Layer of some kind using a tool like Entity Framework
or NHibernate combined with custom code containing domain-specific logic.
ASP.NET MVC 3 provides a number of tools and features to build out application features using only
the definition of model objects. Then when you are ready, you can use tools to construct the
controllers and views for the standard index, create, edit, and delete scenarios for each of the model
objects. The construction work is called scaffolding, but before I talk about scaffolding, you need some
models to work with.

What Is Scaffolding?
Scaffolding in ASP.NET MVC can generate the boilerplate code you need for create, read, update, and
delete (CRUD) functionality in an application. The scaffolding templates can examine the type
definition for a model, and then generate a controller and the controllers associated views. The
scaffolding knows how to name controllers, how to name views, what code needs to go in each
component, and also knows where to place all these pieces in the project for the application to work.
Three scaffolding templates are available in MVC 3. The scaffolding template you select will control
just how far the scaffolding will go with code generation.

Empty Controller
The empty controller template adds a Controller-derived class to the Controllers folder with the name
you specify.

The only action in the controller will be an Index action with no code inside (other than the code to
return a default ViewResult). This template will not create any views.

Controller with Empty Read/Write Actions

This template adds a controller to your project with Index, Details, Create, Edit, and Delete actions.
The actions inside are not entirely empty, but they wont perform any useful work until you add your
own code and create the views for each action.

It generates the Controller without any Views for the Action methods.

public class Person2Controller : Controller

// GET: /Person2/
public ActionResult Index()
return View();
// GET: /Person2/Details/5
public ActionResult Details(int id)
return View();
// GET: /Person2/Create
public ActionResult Create()
return View();
// POST: /Person2/Create

public ActionResult Create(FormCollection collection)
// TODO: Add insert logic here

return RedirectToAction("Index");
return View();

// GET: /Person2/Edit/5
public ActionResult Edit(int id)
return View();
// POST: /Person2/Edit/5
public ActionResult Edit(int id, FormCollection collection)
// TODO: Add update logic here
return RedirectToAction("Index");
return View();
// GET: /Person2/Delete/5
public ActionResult Delete(int id)
return View();
// POST: /Person2/Delete/5
public ActionResult Delete(int id, FormCollection collection)

// TODO: Add delete logic here

return RedirectToAction("Index");
return View();

Controller with Read/Write Actions and Views, Using Entity Framework

This template is the template you are about to select. This template not only generates your controller
with the entire suite of Index, Details, Create, Edit, and Delete actions, but also generates all the
required views and the code to persist and retrieve information from a database. For the template to
generate the proper code, you have to select a model class. The scaffolding examines all the
properties of your model and uses the information it finds to build controllers, views, and data access
code. To generate the data access code, the scaffolding also needs the name of a data context object.
You can point the scaffolding to an existing data context, or the scaffolding can create a new data
context on your behalf.

It will add the Views for each Action (like Create, Delete, Edit, etc.) inside the Views folder along with
CRUD operation logic.

Validation and Annotation

Data annotations are attributes you can find in the System.ComponentModel.DataAnnotations
namespace (although a couple attributes are defined outside this namespace, as you will see).
These attributes provide server-side validation and the framework also supports client-side validation
when you use one of the attributes on a model property. You can use four attributes in the
DataAnnotations namespace to cover common validation scenarios.


Required: Indicates the Column value is expected and value cannot be null. Like all the built-in
validation attributes, the Required attribute delivers both server-side and client-side validation logic.

.. .. ..
public string firstname {set; get;}
public string email {set; get;}
.. .. ..

StringLength: The StringLength attribute can ensure the string value provided by the customer will
fit in the field.

public string FirstName { get; set; }

public string LastName { get; set; }
.. .. ..
Range: The Range attribute specifies minimum and maximum constraints for a numerical value.

.. .. ..
public int Age { get; set; }
.. .. ..
RegularExpression: Regular expressions are an efficient and terse means to enforce the shape and
contents of a string value. If the customer gives you an e-mail address and the regular expression
doesnt think the string looks like an e-mail address, the customer will see the error.

.. .. ..
public string Email { get; set; }
.. .. ..
Compare: The Compare attribute used to compare the value with another property in the same

.. .. ..
[Display(Name = "Password")]
public string Password { get; set; }

[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation
password do not match.")]
public string ConfirmPassword { get; set; }
.. .. ..

Custom Validation
Every validation attribute allows you to pass a named parameter with a custom error message. For
example, you want to display your own error message for Required validation, you are flexible to
perform this operation.

.. .. ..
[Required(ErrorMessage=Your last name is required)]
[StringLength(160, ErrorMessage={0} is too long.)]
public string LastName { get; set; }
.. .. ..
The custom error message can also have a single format item in the string. The built-in attributes
format the error message string using the friendly display name of a property.

.. .. ..
[Required(ErrorMessage=Your {0} is required.)]
[StringLength(160, ErrorMessage={0} is too long.)]
public string LastName { get; set; }
.. .. ..

Display and Edit Annotations

Display: The Display attribute sets the friendly display name for a model property. You can use the
Display attribute to fix the label for the FirstName field:

.. .. ..
[StringLength(160, MinimumLength=3)]
[Display(Name=First Name)]
public string FirstName { get; set; }
.. .. ..

In addition to the name, the Display attribute enables you to control the order in which properties will
appear in the UI.
DisplayFormat: The DisplayFormat attribute handles various formatting options for a property via
named parameters.

.. .. ..
public decimal Total { get; set; }
.. .. ..

ScaffoldColumn: The ScaffoldColumn attribute hides a property from HTML helpers such as
EditorForModel and DisplayForModel:

.. .. ..
public string Username { get; set; }
.. .. ..
With the attribute in place, EditorForModel will no longer display an input or label for the Username

ReadOnly: Place the ReadOnly attribute on a property if you want to make sure the default model
binder does not set the property with a new value from the request.

.. .. ..
public decimal Total { get; set; }
.. .. ..

DataType: The DataType attribute enables you to provide the run time with information about the
specific purpose of a property.

.. .. ..
[Display(Name = Password)]
public string Password { get; set; }
.. .. ..

Ajax and JavaScript

Technically, AJAX stands for asynchronous JavaScript and XML. In practice, AJAX stands for all the
techniques you use to build responsive web applications with a great user experience. ASP.NET MVC 3
is a modern web framework, and like every modern web framework there is support for AJAX right
from the start. The core of the AJAX support comes from the open source jQuery JavaScript library. All
the major AJAX features in ASP.NET MVC 3 build on or extend features in jQuery.

The jQuery tagline is write less, do more, and the tagline is a perfect description of the jQuery
experience. The API is terse, yet powerful. The library itself is flexible, yet lightweight. Best of all,
jQuery supports all the modern browsers. jQuery is one of the most popular JavaScript libraries in
existence, and remains an open source project. You can find the latest download, documentation, and
plugins on the website. jQuery excels at fi nding, traversing, and manipulating HTML
elements inside an HTML document. Once youve found an element, jQuery also makes it easy to wire
up event handlers on the element, animate the element, and build AJAX interactions around the
jQuery includes everything you need to send asynchronous requests back to your web server. You can
generate POST requests or GET requests and jQuery notifies you when the request is complete. With
jQuery, you can send and receive XML data or JavaScript Object Notation (JSON) format. jQuery
makes AJAX easy.
Unobtrusive JavaScript: It is the practice of keeping JavaScript code separate from markup. You
package all the script code you need into .js files. If you look at the source code for a view, you dont
see any JavaScript intruding into the markup. Even when you look at the HTML rendered by a view,
you still dont see any JavaScript inside. The only sign of script youll see is one or more <script> tags
referencing the JavaScript files.

Custom Scripts: When you write your own custom JavaScript code, you can add your code into new
files in the scripts directory.

AJAX helpers are available through the Ajax property inside a Razor view. Like HTML helpers, most of
the methods on this property are extension methods (but for the AjaxHelper type). The ActionLink
method of the Ajax property creates an anchor tag with asynchronous behavior. Ajax.ActionLink
produces something that will take a response from the server and graft new content directly into a
page. The Ajax.ActionLink() helper method returns an anchor element that contains the URL to the
specified action method; when the action link is clicked, the action method is invoked asynchronously
by using JavaScript.
Lets try to create a sample by placing a <Div> on a form and update the content using the Ajax calls
from MVC.
Create an ASP.Net MVC application. In /views/layout/_Layout.cshtml I load the following scripts:

.. .. ..
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js") type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js")type="text/javascript"></script>

.. .. ..

Inside the Home controller added the below action methods.

.. .. ..
public string GetStatus()
return "Status OK at " + DateTime.Now.ToLongTimeString();
public string UpdateForm(string textBox1)
if (textBox1 != "Enter text")
return "You entered: \"" + textBox1.ToString() + "\" at " +

return String.Empty;

.. .. ..
Finally, replace the content of the Index.aspx page, which is added automatically to the Visual Studio
project for ASP.NET MVC. The new Index.aspx page displays the time that the page is rendered, a
status message that has a link for updating the message asynchronously, and a form for submitting a
text string.

ViewBag.Title = "Home Page";
Page Rendered: @DateTime.Now.ToLongTimeString()
<span id="status">No Status</span>
<br />
@Ajax.ActionLink("Update Status", "GetStatus", new
AjaxOptions{UpdateTargetId="status" })
<br /><br />
@using(Ajax.BeginForm("UpdateForm", new
AjaxOptions{UpdateTargetId="textEntered"})) {
@Html.TextBox("textBox1","Enter text")
<input type="submit" value="Submit"/><br />
<span id="textEntered">Nothing Entered</span>

After clicking on Update Status action link.

Now, enter some text in Textbox and Click on Submit.

Unobtrusive JavaScript
Unobtrusive JavaScript (in the MVC3 sense) is a strategy that ensures that no JavaScript is embedded
within the markup.

Jquery UI Autocomplete
jQuery UI is a jQuery plugin that includes both effects and widgets. Like all plugins it integrates
tightly with jQuery and extends the jQuery API.

$(function () {
$(#myImg).mouseover(function () {
$(this).animate({ height: +=25, width: +=25 })
Beyond Helpers x 199
.animate({ height: -=25, width: -=25 });

The first step is to include jQuery UI across your application by adding a new script tag to the layout

<script src=@Url.Content(~/Scripts/jquery-1.4.4.min.js)
<script src=@Url.Content(~/Scripts/jquery.unobtrusive-ajax.min.js)

<script src=@Url.Content(~/Scripts/jquery-ui.min.js)
Now, you can change the code inside the mouseover event handler:

$(function () {
$(#myImg).mouseover(function () {
When users run their mouse across an album image, the album bounces up and down for a short time.
As you can see, the UI plugin extended jQuery by giving you additional methods to execute against
the wrapped set.
You can find out what options are available (and their default values) by reading the plugin
documentation on Additional effects in jQuery UI include explode, fade, shake, and
pulsate. The plugin also includes widgets like accordion, autocomplete, button, datepicker, dialog,
progressbar, slider, and tabs, etc.

Jquery & Ajax

When you need complete control over an AJAX request, you can turn to the jQuery ajax method.
The ajax method takes an options parameter where you can specify the HTTP verb (such as GET
or POST), the timeout, an error handler, and more. All the other asynchronous communication
methods youve seen (load and getJSON) ultimately call down to the ajax method.

$(#empSearch).submit(function (event) {
var form = $(this);
url: form.attr(action),
data: form.serialize(),
beforeSend: function () {
complete: function () {
error: searchFailed,
success: function (data) {
The call to ajax is verbose because you customize quite a few settings. The url and data properties are
just like the parameters you passed to load and getJSON. What the ajax method gives you is the
ability to provide callback functions for beforeSend and complete. You will respectively show and hide
the animated, spinning gif during these callbacks to let the user know a request is outstanding.
jQuery will invoke the complete callback even if the call to the server results in an error. Of the next
two callbacks, error and success, however, only one can win. If the call fails, jQuery calls the

searchFailed error function you alreadydefi ned in the AJAX Forms section. If the call succeeds you
will render the template as before.




Traditionally, in many web frameworks such as Classic ASP, JSP, PHP, and ASP.NET, the URL represents
a physical file on disk. For example, when you see a request for /albums/list.aspx
, you can bet your kids tuition that the website has a directory structure that contains an albums
folder and a List.aspx file within that folder. In this case, there is a direct relationship between the
URL and what physically exists on disk. A request for this URL is received by the web server, which
executes some code associated with this file to produce a response. This 1:1 relationship between
URLs and the file system is not the case with most MVC-based web frameworks, such as ASP.NET
MVC. These frameworks generally take a different approach by mapping the URL to a method call on a
class, rather than some physical file. These classes are generally called controllers because their
purpose is to control the interaction between the user input and other components of the system. And
the methods that serve up the response are generally called actions. These represent the various
actions the controller can process in response to user input requests.
This might feel unnatural to those who are accustomed to thinking of URLs as a means of accessing a
file, but consider the acronym URL itself, Uniform Resource Locator. In this case, Resource is an
abstract concept. It could certainly mean a fi le, but it can also be the result of a method call or
something else entirely. All URLs are technically URIs. The W3C has said, at, that a URL is a useful but informal concept: A URL is a type of URI that
identifies a resource via a representation of its primary access mechanism.

Routing within the ASP.NET MVC framework serves two main purposes:

It matches incoming requests that would not otherwise match a file on the file system and
maps the requests to a controller action.

It constructs outgoing URLs that correspond to controller actions.

To better understand Routing, many developers compare it to URL Rewriting. After all, both
approaches are useful in creating a separation between the incoming URL and what ends up handling
the request and both of these techniques can be used to create pretty URLs for Search Engine
Optimization (SEO) purposes. For example, URL Rewriting is often used for mapping old sets of URLs
to a new set of URLs. Contrast that to routing which is focused on mapping a URL to a resource.
Another key difference is that Routing also helps generate URLs using the same mapping rules that it
uses to match incoming URLs. URL rewriting only applies to incoming requests URLs and does not help
in generating the original URL.

Route URLs
After you create a new ASP.NET MVC Web Application project, take a quick look at the code in
Global.asax.cs. Youll notice that the Application_Start method contains a call to a method named the
RegisterRoutes method. This method is where all routes for the application are registered.

public static void RegisterRoutes(RouteCollection routes)


The parse of this certain URLs into a dictionary of keys and values stored in an instance of a
RouteValueDictionary to give you an idea of how URLs are decomposed by routes into important
pieces of information used later in the request pipeline.




URL Parameter
first = employee
second = display
first = dept
second = loc
first = a.b
second = c-d

This is a pattern-matching rule used to determine if this route applies to an incoming request. In this
example, this rule will match any URL with three segments because a URL parameter, by default,
matches any nonempty value. When this route matches a URL with three segments, the text in the
first segment of that URL corresponds to the {first} URL parameter, the value in the second segment
of that URL corresponds to the {second} URL parameter, and the value in the third segment
corresponds to the {third} parameter.
If you actually make a request to the URLs listed in above table, youll notice that a request for your
application ends up returning a 404 File Not Found error. Although you can define a route with any
parameter names youd like, certain special parameter names are required by ASP.NET MVC in order
to function correctly {controller} and {action}. The value of the {controller} parameter is used to
instantiate a controller class to handle the request. By convention, MVC appends the suffix Controller
to the value of the {controller} URL parameter and attempts to locate a type of that name (case
insensitively) that also implements the System.Web.Mvc.IController interface.
Now, you need to change the route as below so that it contains the MVC-specific URL parameter

routes.MapRoute(simple, {controller}/{action}/{id});
The {action} parameter value is used to indicate which method of the controller to call in order to
handle the current request. Classes that directly implement IController can implement their own
conventions for handling mapping code to handle the request. Any route parameters other than
{controller} and {action} can be passed as parameters to the action method, if they exist. For
example, assuming the following controller:

public class AlbumsController : Controller

public ActionResult Display(int id)
//Do something
return View();
A request for /employee/display/1001 will cause MVC to instantiate this class and call the Display()
method, passing in 123 for the id.

You can define the route like this in Global.asax:

.. .. ..
routes.MapRoute(simple, {controller}/{action}/{id},
new {id = UrlParameter.Optional});
.. .. ..

The {id = UrlParameter.Optional} snippet defines a default value for the {id} parameter.
This default allows this route to match requests for which the id parameter is missing.

Named Routes
Routing in ASP.NET doesnt require that you name your routes, and in many cases it seems to work
just fine without using names. To generate a URL, simply grab a set of route values you have lying
around, hand it to the routing engine, and let the routing engine sort it all out. But as well see in this
section, there are cases where this can break down due to ambiguities between which route should be
chosen to generate a URL. Named routes solve this problem by giving precise control over route
selection when generating URLs.

public static void RegisterRoutes(RouteCollection routes)

name: Test,
url: code/p/{action}/{id},
defaults: new { controller = Section, action = Index, id = }
name: Default,
url: {controller}/{action}/{id},
defaults: new { controller = Home, action = Index, id = }
To generate a hyperlink to each route from within a view, youd write the following code.

new {controller=section, action=Index, id=123})
new {controller=Home, action=Index, id=123})

Multiple URL Parameters in a Segment

A route URL may have multiple parameters per segment.


When matching incoming requests, literals within the route URL are matched exactly. URL parameters
are matched greedily, which has the same connotations as it does with regular expressions. In other
terms, the route tries to match as much text as possible with each URL parameter.

Route URL






Route Data Result


In large ASP.NET MVC3 applications you can potentially have hundreds of controllers. This can become
problematic because the .NET Framework looks in the Controllers folder and all sub-folders looking
for controllers to match up with the defined routes.
To help you organize your code, you can add namespaces to your routes to constrain the controllers
the route will match to particular namespaces. The route below will only use controllers defined in the
Home.NIT namespace.

routes.MapRoute("NamespacedRoute", "Cool/{controller}/{action}",
new { controller = "Home", action = "Index", id =
UrlParameter.Optional } , null,
, new string[] { "Home.NIT" });




Caching in MVC3
ASP.NET platform provides two major caching tools: one is Data Caching via the HttpContext's Cache
object, through which you can cache arbitrary .NET objects; the other is Output Caching, which
records the HTML response sent by an action method, and replays it for subsequent requests to the
same URL, reducing the number of times that your action method code actually runs. With the
underground architecture based on ASP.NET, the ASP.NET MVC framework does not change much in
terms of buffering techniques. Despite this, there are still a couple of details worthy of your great

Output Caching
Output caching plays an important role in terms of modern Web system performance. Under many
cases, it is acceptable for a Web page response to be a little stale if this brings significant performance
advantages. A much better strategy is to create the page once, cache it somewhere, and give the
page output a proper period of duration. Once the cached page becomes stale, the first incoming
request will be served in the standard way, running the page's code, and the new page output will be
cached for another period until it also becomes stale.
As you've imaged, ASP.NET page output caching comes to help. It helps you to cache page responses,
so that following requests can be satisfied without executing the page one more - instead by simply
returning the cached output. Since MVC's caching mechanism is built upon the infrastructure of
ASP.NET cache support, there are quite some resemblance between them. Next, let's look at how
ASP.NET MVC provides output caching support via the OutputCache filter.
The OutputCacheAttribute tells ASP.NET to cache the action method's output so that the same output
will be reused next time the action method is requested, as a result of which the server side
throughput can be greatly increased. As for subsequent requests, it eliminates almost all the
expensive parts of request processing (such as database queries).
The following abstracts the role of each of the above properties:
Duration (int, mandatory): used to specify how long (in seconds) the output remains cached.
VaryByParam (string): used to tell ASP.NET whether to use a different cache entry for each
combination of Request.QueryString and Request.Form values matching these names.
VaryByHeader (string, optional): Tells ASP.NET to use a different cache entry for each combination
of values sent in these HTTP header names.
VaryByCustom (string, optional): If specified, ASP.NET calls the Global.asax.cs file's
GetVaryByCustomString() method passing this arbitrary string value as a parameter, so you can
generate your own cache key. The special value browser is used to vary the cache by the browser's
name and major version data.
VaryByContentEncoding (string, optional): Allows ASP.NET to create a separate cache entry for
each content encoding (e.g., gzip, deflate) that may be requested by a browser.
Location (optional): Specifies where the output is to be cached. This parameter takes one of the
following enumeration values: Server or client.
CacheProfile (string, optional): If specified, instructs ASP.NET to take cache settings from a
particular named <outputCacheSettings> node in Web.config.

SqlDependency (string, optional): under the case that you specify a database and table name pair,
this will result in the cached data to expire automatically when the underlying database data changes.
Order (int, optional): The Order property takes an integer value that must be 0 (the default) or
greater, with one exception.
Lets create a sample with OutputCache for an Action inside a Controller.

[OutputCache(Duration = 60, VaryByParam = "none")]

public ActionResult OutputCacheCase1()
return View();


ViewBag.Title = "myCache";
<h2>Output Cache</h2>
The current time is: @DateTime.Now.ToString("T")

Now if you refresh the same page within 60 seconds, the date & time will be same. Afterwards, it will
get interacts with Server to fetch new date & time details.

Cache Profiles
To create a uniform solution in real scenarios, it is a better choice to configure output cache properties
by creating a cache profile in the web configuration (web.config) file.

By creating one cache profile, we can apply it to any specified controllers or related actions to
avoid code duplication.
We can easily modify the web configuration file without recompiling the application. This is
particularly useful when the system has already been deployed and needs further


<add name="OneMinute" duration="60" varyByParam="none" />

using System;
using System.Web.Mvc;
namespace MvcApplication1.Controllers

public class ProfileController : Controller

public string ProfileTest()
return DateTime.Now.ToString("T");

VaryByHeader and VaryByCustom

In real cases, VaryByHeader and VaryByCustom are mainly used to customize the appearance or
content of the page accessed by the client. For instance, one URL may need to provide rendering
output for both browser and mobile phone client simultaneously. Under such a circumstance, we need
to provide different caching content versions for different client sides.

[OutputCache(Duration = 60,
VaryByParam = "none",
VaryByHeader = "browser")]
public ActionResult OutputCacheCaseForHeaderAndCustom()
return View();

Partial Output Caching

In addition to supporting full page output caching, ASP.NET MVC 3 has also provided supports for
partial-page caching which allows you to cache a part of output and re-use it across multiple
requests or controllers.
Moreover, the OutputCache feature for partial-page caching has been updated in ASP.NET MVC 3, so
that sub-content cached entries are varied based on input parameters as opposed to the URL structure
of the top-level request, which makes caching scenarios both easier and more powerful than that in
the previous version.

It is very important to keep in mind that the cache is shared among all of the users of your
application. This means if your partial view renders data specific to User A, User B will see User A's
data unless you have some specific mechanism in place to keep them separated such as the
SessionID. In general, however, it's not very efficient to cache anything on a per-user basis. The
amount of server resources consumed per-user could quickly get out of control. As a result of this
consideration, it's highly recommended to only cache things that are not user specific.

ASP.Net MVC4 Features

MVC Release History
The Current Version of ASP.NET MVC is 4 and it was released on 15th Aug 2012. ASP.NET MVC 4 is
packaged with Visual Studio 2012 and MVC 4 can be installed for Visual Studio 2010. Below I have
mentioned the release history of ASP.NET MVC.



Dec 07
Mar 09
Dec 09
Feb 10
Mar 10
Oct 10
Nov 10
Dec 10
Jan 11

20 Sep 11
15 Feb 12
31 May 12
15 Aug 12



ASP.NET MVC 4 Developer

New MVC4 Project Templates

1) Open Visual Studio 2012.
2) Select the File New Project menu command. In the New Project dialog, select the Visual
C# Web template on the left pane tree, and choose ASP.NET MVC 4 Web Application. Name
the project, select a location (or leave the default) and click OK.

3) In the New ASP.NET MVC 4 Project dialog, select the Internet Application project
template and click OK. Make sure you have selected Razor as the view engine.

4) Now Visual Studio created our project in place and the solution file looks like below in Solution

Press F5 to run the solution and see the renewed templates. You can check out the following features:
Modern-style templates: The templates have been renewed, providing more modern-looking styles.

MVC4 restyled templates

Adaptive Rendering: Check out resizing the browser window and notice how the page layout
dynamically adapts to the new window size. These templates use the adaptive rendering technique to
render properly in both desktop and mobile platforms without any customization.

Richer UI with JavaScript: Another enhancement to default project templates is the use of
JavaScript to provide a more interactive JavaScript. The Login and Register links used in the template
exemplify how to use the jQuery UI Dialog to display a fancy login screen.

HTML 5 Markup: Browse template views to find out the new theme markup.
Updated JavaScript libraries: The MVC4 default template now includes KnockoutJS, a JavaScript
MVVM framework that lets you create rich and highly responsive web applications using JavaScript and
HTML. Like in MVC3, jQuery and jQuery UI libraries are also included in ASP.NET MVC 4.
ASP.NET Universal providers included in the solution: ASP.NET Universal Providers extend
Session, Membership, Roles and Profile support to SQL Compact Edition and SQL Azure. By only
configuring the right connection string, your application will be able to work with SQL Server (plus
Express), SQL Server Compact or SQL Azure.

Project Templates
Currently MVC 4 Application in Visual Studio 2010 and Visual Studio 2012 offers 6 different types of
project templates.

Empty Template: It contains the minimum references required for ASP.Net MVC application. The
Models, Controllers, App_Data completely empty folders.
Basic Template: In addition to Empty template, this Basic template contains below content.
Content folder
Script folder
Shared folder inside Views folder
App_Start folder
Internet Application: Along with Basic template, this contains Home & Account Controllers and
necessary Views for the same.
Intranet Application: This template is same like the Internet Application template, except that it is
preconfigured to use Windows-based authentication.
Mobile Application: This template, however, is optimized for mobile devices and includes the jQuery
Mobile JavaScript framework and views that apply the HTML that works best with jQuery Mobile.
Web API: The Web API template is yet another variation of the Internet Application template that
includes a preconfigured Web API controller.ASP.NET Web API is a framework that makes it easy to
build HTTP services that reach a broad range of clients, including browsers and mobile devices.
ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

Exploring the Mobile Application Template

ASP.NET MVC 4 facilitates the development of websites for mobile and tablet browsers. This template
has the same application structure as the Internet Application template (notice that the controller code
is practically identical), but its style was modified to render properly in touch-based mobile devices.

Now you are able to explore the solution and check out some of the new features introduced by the
MVC 4 solution template for mobile:
jQuery Mobile Library: The Mobile Application project template includes the jQuery Mobile library,
which is an open source library for mobile browser compatibility. jQuery Mobile applies progressive
enhancement to mobile browsers that support CSS and JavaScript. Progressive enhancement enables
all browsers to display the basic content of a web page, while it only enables the most powerful
browsers to display the rich content. The JavaScript and CSS files, included in the jQuery Mobile style,
help mobile browsers to fit the content in the screen without making any change in the page markup.

Press F5 to run the solution.

Open the Windows Phone 7 Emulator, located in Start Menu All Programs Windows Phone SDK
7.1 Windows Phone Emulator.
In the phone start screen, open Internet Explorer. Check out the URL where the desktop application
started and browse to that URL from the phone. Now you are able to enter the login page or check
out the about page. Notice that the style of the website is based on the new Metro app for mobile.