What Is MVC?: View Controller Model
What Is MVC?: View Controller Model
What Is MVC?: View Controller Model
This article on Interview Questions and Answers of MVC basically covers most of the MVC 2, MVC
3 and MVC 4 topics that are most likely to be asked in job interviews/tests/exams.
The sole purpose of this article is to sum up important questions and answers that can be used
by developers to brush-up all about MVC before they take any interview of the same kind.
What is MVC?
MVC is a framework pattern that splits an application’s implementation logic into three
component roles: models, views, and controllers.
Model: The business entity on which the overall application operates. Many applications use a
persistent storage mechanism (such as a database) to store data. MVC does not specifically
mention the data access layer because it is understood to be encapsulated by the Model.
View: The user interface that renders the Model into a form of interaction.
Controller: Handles a request from a View and updates the Model that results in a change of the
Model's state.
To implement MVC in .NET, we need mainly three classes (View, Controller and the Model).
The architecture is self explanatory. The browser (as usual) sends a request to IIS, IIS searches for
the route defined in MVC application and passes the request to the controller as per route, the
controller communicates with the model and passes the populated model (entity) to View (front
end), Views are populated with model properties, and are rendered on the browser, passing the
response to browser through IIS via controllers which invoked the particular View.
ASP.NET MVC 2 was released in March 2010. Its main features are:
Introduction of 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
There were also lots of API enhancements and “pro” features, based on feedback from
developers building a variety of applications on ASP.NET MVC 1, such as:
o Support for partitioning large applications into areas
o Asynchronous controllers support
o Support for rendering subsections of a page/site using Html.RenderAction
o Lots of new helper functions, utilities, and API enhancements
ASP.NET MVC 3 shipped just 10 months after MVC 2 in Jan 2011. Some of the top features in
MVC 3 included:
1. App initialization
2. Routing
3. Instantiate and execute controller
4. Locate and invoke controller action
5. Instantiate and render view
As per Wikipedia, 'the process of breaking a computer program into distinct features that overlap
in functionality as little as possible'. MVC design pattern aims to separate content from
presentation and data-processing from content.
When we talk about Views and Controllers, their ownership itself explains separation. The views
are just the presentation form of an application, it does not have to know specifically about the
requests coming from controller. The Model is independent of View and Controllers, it only holds
business entities that can be passed to any View by the controller as required for exposing them
to the end user. The controller is independent of Views and Models, its sole purpose is to handle
requests and pass it on as per the routes defined and as per the need of rendering views. Thus
our business entities (model), business logic (controllers) and presentation logic (views) lie in
logical/physical layers independent of each other.
Razor is the first major update to render HTML in MVC3. Razor was designed specifically as a
view engine syntax. It has one main focus: code-focused templating for HTML generation. Here’s
how that same markup would be generated using Razor:
The Razor syntax is easier to type, and easier to read. Razor doesn’t have the XML-like heavy
syntax. of the Web Forms view engine.
It’s got semantic meaning, and all of it — the tag structure, element attributes, and so on —
should have a precise meaning. Strewing JavaScript gunk across the page to facilitate interaction
(I’m looking at you, __doPostBack!) harms the content of the document.
MVC 3 included JavaScript Object Notation (JSON) binding support via the
new JsonValueProviderFactory, enabling the action methods to accept and model-bind
data in JSON format. This is especially useful in advanced Ajax scenarios like client templates and
data binding that need to post data back to the server.
MVC 3 introduced a new concept called a dependency resolver, which greatly simplified the use
of dependency injection in your applications. This made it easier to decouple application
components, making them more configurable and easier to test.
Display modes use a convention-based approach to allow selecting different views based on the
browser making the request. The default view engine first looks for views with names ending
with .Mobile.cshtml when the browser’s user agent indicates a known mobile device. For example,
if we have a generic view titled Index.cshtml and a mobile view titled Index.Mobile.cshtml, MVC 4
will automatically use the mobile view when viewed in a mobile browser.
Additionally, we can register your own custom device modes that will be based on your own
custom criteria — all in just one code statement. For example, to register a WinPhone device
mode that would serve views ending with.WinPhone.cshtml to Windows Phone devices, you’d use
the following code in the Application_Start method of your Global.asax:
AuthConfig.cs is used to configure security settings, including sites for OAuth login.
BundleConfig.cs in MVC4 is used to register bundles used by the bundling and minification
system. Several bundles are added by default, including jQuery, jQueryUI, jQuery validation,
Modernizr, and default CSS references.
This is used to register global MVC filters. The only filter registered by default is
the HandleErrorAttribute, but this is a great place to put other filter registrations.
RouteConfig.cs holds the granddaddy of the MVC config statements, Route configuration.
Used to register Web API routes, as well as set any additional Web API configuration settings.
Previously (in MVC3 and MVC2), the Visual Studio Add Controller menu item only displayed when
we right-clicked on the Controllers folder. However, the use of the Controllers folder was purely
for organization. (MVC will recognize any class that implements the IController interface as
a Controller, regardless of its location in your application.) The MVC 4 Visual Studio tooling
has been modified to display the Add Controller menu item for any folder in your MVC project.
This allows us to organize your controllers however you would like, perhaps separating them into
logical groups or separating MVC and Web API controllers.
Windows XP
Windows Vista
Windows 7
Windows 8
MVC 4 development tooling is included with Visual Studio 2012 and can be installed on Visual
Studio 2010 SP1/Visual Web Developer 2010 Express SP1.
What are the various types of Application Templates used to create an MVC
application?
1. The Internet Application template: This contains the beginnings of an MVC web application —
enough so that you can run the application immediately after creating it and see a few pages.
This template also includes some basic account management functions which run against the
ASP.NET Membership.
2. The Intranet Application template: The Intranet Application template was added as part of the
ASP.NET MVC 3 Tools Update. It is similar to the Internet Application template, but the account
management functions run against Windows accounts rather than the ASP.NET Membership
system.
3. The Basic template: This template is pretty minimal. It still has the basic folders, CSS, and MVC
application infrastructure in place, but no more. Running an application created using the Empty
template just gives you an error message.
Why use Basic template? The Basic template is intended for experienced MVC developers who
want to set up and configure things exactly how they want them.
4. The Empty template: The Basic template used to be called the Empty template, but developers
complained that it wasn’t quite empty enough. With MVC 4, the previous Empty template was
renamed Basic, and the new Empty template is about as empty as we can get. It has the
assemblies and basic folder structure in place, but that’s about it.
5. The Mobile Application template: The Mobile Application template is preconfigured with jQuery
Mobile to jump-start creating a mobile only website. It includes mobile visual themes, a touch-
optimized UI, and support for Ajax navigation.
6. The Web API template: ASP.NET Web API is a framework for creating HTTP services. The Web API
template is similar to the Internet Application template but is streamlined for Web API
development. For instance, there is no user account management functionality, as Web API
account management is often significantly different from standard MVC account management.
Web API functionality is also available in the other MVC project templates, and even in non-MVC
project types.
What are the default Top level directories created when adding MVC4
application?
Note: Some of the content has been taken from various books/articles.
This namespace contains classes and interfaces that support the MVC pattern for ASP.NET Web
applications. This namespace includes classes that represent controllers, controller factories,
action results, views, partial views, and model binders.
System.Web.Mvc.Html namespace contains classes that help render HTML controls in an MVC
application. This namespace includes classes that support forms, input controls, links, partial
views, and validation.
MVC provides us ViewData, ViewBag and TempData for passing data from controller, view and
in next requests as well. ViewData and ViewBag are similar to some extent
but TempData performs additional roles.
What are the roles and similarities between ViewData and ViewBag?
What are the differences between ViewData and ViewBag? (taken from a
blog)
NOTE: Although there might not be a technical advantage to choosing one format over the
other, there are some critical differences to be aware of between the two syntaxes.
One obvious difference is that ViewBag works only when the key being accessed is a valid C#
identifier. For example, if you place a value in ViewData["KeyWith Spaces"], you can’t access
that value using ViewBag because the codewon’t compile.
Another key issue to be aware of is that dynamic values cannot be passed in as parameters to
extension methods. The C# compiler must know the real type of every parameter at compile time
in order for it to choose the correct extension method.
If any parameter is dynamic, compilation will fail. For example, this code will always
fail: @Html.TextBox("name", ViewBag.Name). To work around this, either
use ViewData["Name"] or cast the value to a specific type: (string) ViewBag.Name.
What is TempData?
TempData is a dictionary derived from the TempDataDictionary class and stored in short
lives session. It is astring key and object value.
It keeps the information for the time of an HTTP Request. This means only from one page to
another. It helps to maintain data when we move from one controller to another controller or
from one action to other action. In other words, when we redirect Tempdata helps to maintain
data between those redirects. It internally uses session variables. Temp data use during the
current and subsequent request only means it is used when we are sure that the next request will
be redirecting to next view. It requires typecasting for complex data type and checks for null
values to avoid error. Generally it is used to store only one time messages like error messages,
validation messages.
How can you define a dynamic property with the help of viewbag in
ASP.NET MVC?
Assign a key name with syntax, ViewBag.[Key]=[ Value] and value using equal to operator.
For example, you need to assign list of students to the dynamic Students property of ViewBag.
Collapse | Copy Code
List<string> students = new List<string>();
countries.Add("Akhil");
countries.Add("Ekta");
ViewBag.Students = students;
//Students is a dynamic property associated with ViewBag.
Note: Some of the content has been taken from various books/articles.
Accepted a view model represents data that you want to have displayed on your view/page.
Let's say that you have an Employee class that represents your employee domain model and it
contains the following 4 properties:
View models differ from domain models in that view models only contain the data (represented
by properties) that you want to use on your view. For example, let's say that you want to add a
new employee record, your view model might look like this:
As you can see, it only contains 2 of the properties of the employee domain model. Why is this
you may ask? Idmight not be set from the view, it might be auto generated by
the Employee table. AndDateCreated might also be set in the stored procedure or in the
service layer of your application. So Id and DateCreated is not needed in the view model.
When loading the view/page, the create action method in your employee controller will create an
instance of this view model, populate any fields if required, and then pass this view model to the
view:
return View(viewModel);
}
Your view might look like this (assuming you are using ASP.NET MVC3 and razor):
<table>
<tr>
<td><b>First Name:</b></td>
<td>@Html.TextBoxFor(x => x.FirstName, new { maxlength = "50", size = "50" })
@Html.ValidationMessageFor(x => x.FirstName)
</td>
</tr>
<tr>
<td><b>Last Name:</b></td>
<td>@Html.TextBoxFor(x => x.LastName, new { maxlength = "50", size = "50" })
@Html.ValidationMessageFor(x => x.LastName)
</td>
</tr>
</table>
Validation would thus be done only on FirstName and LastName. Using Fluent Validation, you
might have validation like this:
The key thing to remember is that the view model only represents the data that you want use.
You can imagine all the unneccessary code and validation if you have a domain model with 30
properties and you only want to update a single value. Given this scenario, you would only have
this one value/property in the view model and not the whole domain object.
The solution is independent of MVC.NET framework and is global across server side technologies.
Most modern AJAX applications utilize XmlHTTPRequest to send async request to the server.
Such requests will have distinct request header:
MVC.NET provides helper function to check for ajax requests which internally inspects X-
Requested-With request header to set IsAjax flag.
These templates use the Visual Studio T4 templating system to generate a view based on the
model type selected. Scaffolding in ASP.NET MVC can generate the boilerplate code we need for
create, read, update, and delete (CRUD) functionality in an application. The scaffolding templates
can examine the type definition for, and then generate a controller and the controller’s
associated views. The scaffolding knows how to name controllers, how to name views, what code
needs to go in each component, and where to place all these pieces in the project for the
application to work.
Code expressions in Razor are always HTML encoded. This Web Forms syntax also automatically
HTML encodes the value.
Unlike code expressions, which are evaluated and outputted to the response, blocks of code are
simply sections of code that are executed. They are useful for declaring variables that we may
need to use later.
Razor
Web Forms
HelperPage.IsAjax gets a value that indicates whether Ajax is being used during the request
of the Web page.
Namespace: System.Web.WebPages
Assembly: System.Web.WebPages.dll
Explain combining text and markup in Views with the help of an example?
This example shows what intermixing text and markup looks like using Razor as compared to
Web Forms:
Razor
Web Forms
In simple terms, a repository basically works as a mediator between our business logic layer and
our data access layer of the application. Sometimes, it would be troublesome to expose the data
access mechanism directly to business logic layer, it may result in redundant code for accessing
data for similar entities or it may result in a code that is hard to test or understand. To overcome
these kinds of issues, and to write an Interface driven and test driven code to access data, we use
Repository Pattern. The repository makes queries to the data source for the data, thereafter maps
the data from the data source to a business entity/domain object, finally and persists the changes
in the business entity to the data source. According to MSDN, a repository separates the business
logic from the interactions with the underlying data source or Web service. The separation
between the data and business tiers has three benefits:
In Repository, we write our whole business logic of CRUD operations with the help of Entity
Framework classes, that will not only result in meaningful test driven code but will also reduce
our controller code of accessing data.
A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as
an .aspx file in a Web Forms application. Routing module is responsible for mapping incoming
browser requests to particular MVC controller actions.
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.
Layouts in Razor help maintain a consistent look and feel across multiple views within our
application. As compared to Web Forms, layouts serve the same purpose as master pages, but
offer both a simpler syntax and greater flexibility.
We can use a layout to define a common template for your site (or just part of it). This template
contains one or more placeholders that the other views in your application provide content for. In
some ways, it’s like an abstract base class for your views.
What is ViewStart?
For group of views that all use the same layout, this can get a bit redundant and harder to
maintain.
The _ViewStart.cshtml page can be used to remove this redundancy. The code within this file is
executed before the code in any view placed in the same directory. This file is also recursively
applied to any view within a subdirectory.
When we create a default ASP.NET MVC project, we find there is already a _ViewStart .cshtml file
in the Viewsdirectory. It specifies a default layout:
Because this code runs before any view, a view can override the Layout property and choose a
different one. If a set of views shares common settings, the _ViewStart.cshtml file is a useful place
to consolidate these common view settings. If any view needs to override any of the common
settings, the view can set those values to another value.
Note: Some of the content has been taken from various books/articles.
HTML helpers are methods we can invoke on the HTML property of a view. We also have access
to URL helpers (via the Url property), and AJAX helpers (via the Ajax property). All these helpers
have the same goal: to make views easy to author. The URL helper is also available from within
the controller. Most of the helpers, particularly the HTML helpers, output HTML markup. For
example, the BeginForm helper is a helper we can use to build a robust form tag for our search
form, but without using lines and lines of code:
What is Html.ValidationSummary?
The first error is a model-level error, because you didn’t provide a key (or provided an empty key)
to associate the error with a specific property. The second error you associated with
the Title property, so in your view it will not display in the validation summary area (unless you
remove the parameter to the helper method, or change the value to false). In this scenario, the
helper renders the following HTML:
Other overloads of the ValidationSummary helper enable you to provide header text and set
specific HTML attributes.
NOTE: By convention, the ValidationSummary helper renders the CSS class validation-
summary-errors along with any specific CSS classes you provide. The default MVC project
template includes some styling to display these items in red, which you can change in styles.css.
What is Html.Partial?
The Partial helper renders a partial view into a string. Typically, a partial view contains
reusable markup you want to render from inside multiple different views. Partial has four
overloads:
What is Html.RenderPartial?
The RenderPartial helper is similar to Partial, but RenderPartial writes directly to the
response output stream instead of returning a string. For this reason, you must
place RenderPartial inside a code block instead of a code expression. To illustrate, the
following two lines of code render the same output to the output stream:
There are different ways for returning/rendering a view in MVC Razor. E.g. return View(),
returnRedirectToAction(), return Redirect() and return RedirectToRoute().
Conclusion
I hope we covered a lot of questions to brush-up. Since MVC is very vast now, I know we have
missed a lot stuff too. The content in the question and answer form is also taken from few
renowned books like Professional ASP.NET MVC4 from Wrox, and few of the content is taken
from my MVC articles posted earlier. My upcoming articles will provide interview questions
for EntityFramework too.
ASP.NET MVC is a web development framework from Microsoft that is based on MVC (Model-
View-Controller) architectural design pattern. Microsoft has streamlined the development of MVC
based applications using ASP.NET MVC framework.
5. Can you please explain the request flow in ASP.NET MVC framework?
Request hits the controller coming from client. Controller plays its role and decides which model
to use in order to serve the request further passing that model to view which then transforms the
model and generates an appropriate response that is rendered to the client.
In case of a typical ASP.NET application, incoming requests are mapped to physical files such
as .aspx file. ASP.NET MVC framework uses friendly URLs that more easily describe user’s action
but are not mapped to physical files.
ASP.NET MVC framework uses a routing engine, that maps URLs to controller classes. We can
define routing rules for the engine, so that it can map incoming request URLs to appropriate
controller.
Practically, when a user types a URL in a browser window for an ASP.NET MVC application and
presses “go” button, routing engine uses routing rules that are defined in Global.asax file in order
to parse the URL and find out the path of corresponding controller.
In order to pass data from controller to view and in next subsequent request, ASP.NET MVC
framework provides different options i.e., ViewData, ViewBag and TempData.
Both ViewBag and ViewData are used to communicate between controller and corresponding
view. But this communication is only for server call, it becomes null if redirect occurs. So, in
short, it's a mechanism to maintain state between controller and corresponding view.
ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0
feature). ViewData being adictionary object is accessible using strings as keys and also
requires typecasting for complex types. On the other hand, ViewBag doesn't have typecasting
and null checks.
TempData is also a dictionary object that stays for the time of an HTTP Request.
So, Tempdata can be used to maintain data between redirects, i.e., from one controller to the
other controller.
I already explained about request flow in ASP.NET MVC framework that request coming from
client hits controller first. Actually MVC application determines the corresponding controller by
using routing rules defined in Global.asax. And controllers have specific methods for each user
actions. Each request coming to controller is for a specific ActionMethod. The following code
example, “ShowBooks” is an example of an Action method.
One of the core features of ASP.NET MVC is that it separates the input and UI logic from business
logic. Role of Model in ASP.NET MVC is to contain all application logic including validation,
business and data access logic except view, i.e., input and controller, i.e., UI logic.
Model is normally responsible for accessing data from some persistent medium like database and
manipulate it.
If we need to apply some specific logic before or after action methods, we use action filters. We
can apply these action filters to a controller or a specific controller action. Action filters are
basically custom classes that provide a means for adding pre-action or post-action behavior to
controller actions.
For example:
Below are the steps how control flows in MVC (Model, view and controller) architecture:-
MVC architecture is suited for web application than windows. For window application MVP i.e.
“Model view presenter” is more
applicable.IfyouareusingWPFandSLMVVMismoresuitableduetobindings.
Separation of concerns is achieved as we are moving the code behind to a separate class file. By
moving the binding code to a separate class file we can reuse the code to a great extent.
Automated UI testing is possible because now the behind code (UI interaction code) has moved
to a simple.NET class. This gives us opportunity to write unit tests and automate manual testing.
Is MVC different from a 3 layered architecture?
When this note was written, four versions where released of MVC. MVC 1 , MVC 2, MVC 3 and
MVC 4. So the latest is MVC 4.
Below is a detail table of differences. But during interview it’s difficult to talk about all of them
due to time limitation. So I have highlighted important differences which you can run through
before the interviewer.
Routing helps you to define a URL structure and map the URL with the controller.
For instance let’s say we want that when any user types
“http://localhost/View/ViewCustomer/”, it goes to the “Customer” Controller and invokes
“DisplayCustomer” action. This is defined by adding an entry in to the “routes” collection using
the “maproute” function. Below is the under lined code which shows how the URL structure and
mapping with controller and action is defined.
Yes , you can , you just need to make two entries with different key names and specify the same
controller and action.
How can we navigate from one view to other view using hyperlink?
By using “ActionLink” method as shown in the below code. The below code will create a simple
URL which help to navigate to the “Home” controller and invoke the “GotoHome” action.
Temp data: -Helps to maintain data when you move from one controller to other controller or
from one action to other action. In other words when you redirect,“tempdata” helps to maintain
data between those redirects. It internally uses session variables.
View data: - Helps to maintain data when you move from controller to view.
View Bag: - It’s a dynamic wrapper around view data. When you use “Viewbag” type casting is
not required. It uses the dynamic keyword internally.
Figure:-dynamic keyword
Session variables: - By using session variables we can maintain data from any entity to any
entity.
Hidden fields and HTML controls: - Helps to maintain data from UI to controller only. So you
can send data from HTML controls or hidden fields to the controller using POST or GET HTTP
methods.
Partial view is a reusable view (like a user control) which can be embedded inside other view. For
example let’s say all your pages of your site have a standard structure with left menu, header and
footer as shown in the image below.
Figure:- partial views in MVC
For every page you would like to reuse the left menu, header and footer controls. So you can go
and create partial views for each of these items and then you call that partial view in the main
view.
How did you create partial view and consume the same?
When you add a view to your project you need to check the “Create partial view” check box.
Figure:-createpartialview
Once the partial view is created you can then call the partial view in the main view using
“Html.RenderPartial” method as shown in the below code snippet.
Collapse | Copy Code
<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>
One of the easy ways of doing validation in MVC is by using data annotations. Data annotations
are nothing but attributes which you can be applied on the model properties. For example in the
below code snippet we have a simple “customer” class with a property “customercode”.
In order to display the validation error message we need to use “ValidateMessageFor” method
which belongs to the “Html” helper class.
Later in the controller we can check if the model is proper or not by using “ModelState.IsValid”
property and accordingly we can take actions.
What are the other data annotation attributes for validation in MVC?
In case you want to use regular expression, you can use “RegularExpression” attribute.
If you want to check whether the numbers are in range, you can use the “Range” attribute.
Some time you would like to compare value of one field with other field, we can use the
“Compare” attribute.
In case you want to get a particular error message , you can use the “Errors” collection.
Collapse | Copy Code
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;
If you have created the model object yourself you can explicitly call “TryUpdateModel” in your
controller to check if the object is valid or not.
In case you want add errors in the controller you can use “AddModelError” function.
It’s a light weight view engine. Till MVC we had only one view type i.e.ASPX, Razor was
introduced in MVC 3.
Razor is clean, lightweight and syntaxes are easy as compared to ASPX. For example in ASPX to
display simple time we need to write.
As per Microsoft razor is more preferred because it’s light weight and has simple syntaxes.
For windows authentication you need to go and modify the “web.config” file and set
authentication mode to windows.
Then in the controller or on the action you can use the “Authorize” attribute which specifies
which users have access to these controllers and actions. Below is the code snippet for the same.
Now only the users specified in the controller and action can access the same.
Forms authentication is implemented the same way as we do in ASP.NET. So the first step is to
set authentication mode equal to forms. The “loginUrl” points to a controller here rather than
page.
All the other actions need to be attributed with “Authorize” attribute so that any unauthorized
user if he makes a call to these controllers it will redirect to the controller ( in this case the
controller is “Login”) which will do authentication.
Ajax libraries
Jquery
Below is a simple sample of how to implement Ajax by using “Ajax” helper library. In the below
code you can see we have a simple form which is created by using “Ajax.BeginForm” syntax. This
form calls a controller action called as “getCustomer”. So now the submit action click will be an
asynchronous ajax call.
In case you want to make ajax calls on hyperlink clicks you can use “Ajax.ActionLink” function as
shown in the below code.
So if you want to create Ajax asynchronous hyperlink by name “GetDate” which calls the
“GetDate” function on the controller , below is the code for the same. Once the controller
responds this data is displayed in the HTML DIV tag by name “DateDiv”.
Below is the controller code. You can see how “GetDate” function has a pause of 10 seconds.
The second way of making Ajax call in MVC is by using Jquery. In the below code you can see we
are making an ajax POST call to a URL “/MyAjax/getCustomer”. This is done by using “$.post”. All
this logic is put in to a function called as “GetData” and you can make a call to the “GetData”
function on a button or a hyper link click event as you want.
“ActionResult” can be used to exploit polymorphism and dynamism. So if you are returning
different types of view dynamically “ActionResult” is the best thing. For example in the below
code snippet you can see we have a simple action called as “DynamicView”. Depending on the
flag (“IsHtmlView”) it will either return “ViewResult” or “JsonResult”.
“ActionFilters” helps you to perform logic while MVC action is executing or after a MVC action
has executed.
The problem with inline action attribute is that it cannot be reused across controllers. So we can
convert the inline action filter to an action filter attribute. To create an action filter attribute we
need to inherit from “ActionFilterAttribute” and implement “IActionFilter” interface as shown in
the below code.
Later we can decorate the controllers on which we want the action attribute to execute. You can
see in the below code I have decorated the “Default1Controller” with “MyActionAttribute” class
which was created in the previous code.
Let’ say we want to create a custom view engine where in the user can type a command like
“<DateTime>” and it should display the current date and time.
Step 1:- We need to create a class which implements “IView” interface. In this class we should
write the logic of how the view will be rendered in the “render” function. Below is a simple code
snippet for the same.
Step 2 :-We need to create a class which inherits from “VirtualPathProviderViewEngine” and in
this class we need to provide the folder path and the extension of the view name. For instance for
razor the extension is “cshtml” , for aspx the view extension is “.aspx” , so in the same way for our
custom view we need to provide an extension. Below is how the code looks like. You can see the
“ViewLocationFormats” is set to the “Views” folder and the extension is “.myview”.
Step 3:- We need to register the view in the custom view collection. The best place to register
the custom view engine in the “ViewEngines” collection is the “global.asax” file. Below is the code
snippet for the same.
Below is a simple output of the custom view written using the commands defined at the top.
Figure:-customviewengineusingMVC
If you invoke this view you should see the following output.
In MVC we have “JsonResult” class by which we can return back data in JSON format. Below is a
simple sample code which returns back “Customer” object in JSON format using “JsonResult”.
Below is the JSON output of the above code if you invoke the action via the browser.
What is “WebAPI”?
HTTP is the most used protocol.For past many years browser was the most preferred client by
which we can consume data exposed over HTTP. But as years passed by client variety started
spreading out. We had demand to consume data on HTTP from clients like
mobile,javascripts,windows application etc.
For satisfying the broad range of client “REST” was the proposed approach. You can read more
about “REST” from WCF chapter.
“WebAPI” is the technology by which you can expose data over HTTP following REST principles.
But WCF SOAP also does the same thing, so how does “WebAPI”
differ?
WCF was brought in to implement SOA, never the intention was to implement REST."WebAPI'" is
built from scratch and the only goal is to create HTTP services using REST. Due to the one point
focus for creating “REST” service “WebAPI” is more preferred.
Step 2:- Once you have created the project you will notice that the controller now inherits from
"ApiController" and you can now implement "post","get","put" and "delete" methods of HTTP
protocol.
Step 3:-If you make a HTTP GET call you should get the below results.
DOTNET MVC 4 Basic Interview Questions and Answers for Freshers and Experienced
Developers
Below is the list of dotnet MVC 4 basic interview questions and answers. These MVC interview
questions and answers are meant for freshers as well as for experienced developers. So, If you going
for an interview on MVC, I suggest you to must give a look at following MVC interview questions.
These MVC interview questions are based on basic introduction to MVC, why we need MVC,
components of MVC, MVC namespaces, lifecycle of MVC application and a lot more. So lets have a
look on following basic dotnet MVC interview questions and answers.
1. What is MVC?
MVC is a framework methodology that divides an application’s implementation into three component
roles: models, views, and controllers.
1. M - Model
2. V - View
3. C - Controller
“Models” in a MVC based application are the components of the application that are responsible for
maintaining state. Often this state is persisted inside a database (for example: we might have a
Product class that is used to represent order data from the Products table inside SQL).
“Views” in a MVC based application are the components responsible for displaying the application’s
user interface. Typically this UI is created off of the model data (for example: we might create an
Product “Edit” view that surfaces textboxes, dropdowns and checkboxes based on the current state of
a Product object).
“Controllers” in a MVC based application are the components responsible for handling end user
interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a MVC
application the view is only about displaying information – it is the controller that handles and
responds to user input and interaction.
Model: Model represents the application data domain. In short the applications business logic is
contained with in the model.
View: Views represent the user interface, with which the end users interact. In short the all the user
interface logic is contained with in the UI.
Controller: Controller is the component that responds to user actions. Based on the user actions, the
respective controller, work with the model, and selects a view to render that displays the user
interface. The user input logic is contained with in the controller.
System.Web.Mvc
4- What is the greatest advantage of using asp.net mvc over asp.net webforms?
It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.
5- Which approach provides better support for test driven development - ASP.NET MVC or
ASP.NET Webforms?
ASP.NET MVC
Razor view engine is a new view engine created with ASP.Net MVC model using specially designed
Razor parser to render the HTML out of dynamic server side code. It allows us to write Compact,
Expressive, Clean and Fluid code with new syntax to include server side code in to HTML.
1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
2. Complex applications can be easily managed
3. Separation of concerns. Different aspects of the application can be divided into Model, View and
Controller.
4. ASP.NET MVC views are light weight, as they don't use viewstate.
8- Is it possible to unit test an MVC application without running the controllers in an ASP.NET
process?
Yes, all the features in an asp.net MVC application are interface based and hence mocking is much
easier. So, we don't have to run the controllers in an ASP.NET process for unit testing.
System.Web.Mvc namespace
Contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This
namespace includes classes that represent controllers, controller factories, action results, views,
partial views, and model binders.
System.Web.Mvc.Ajax namespace
Contains classes that support Ajax scripts in an ASP.NET MVC application. The namespace includes
support for Ajax scripts and Ajax option settings.
System.Web.Mvc.Async namespace
Contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application.
System.Web.Mvc.Html namespace
Contains classes that help render HTML controls in an MVC application. The namespace includes
classes that support forms, input controls, links, partial views, and validation.
Yes, put the view into the shared folder. This will automatically make the view available across
multiple controllers.
The controller responds to user interactions, with the application, by selecting the action method to
execute and selecting the view to render.
12- Where are the routing rules defined in an asp.net MVC application?
The following are just a few return types of a controller action method. In general an action method
can return an instance of a any class that derives from ActionResult class.
1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult
In general, all public methods of a controller class are treated as action methods. If you want prevent
this default behavior, just decorate the public method with NonActionAttribute.
ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action
methods. ASP.NET Routing makes use of route table. Route table is created when your web
application first starts. The route table is present in the Global.asax file.
When an MVC application first starts, the Application_Start() method is called. This method, in turn,
calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.
18- What are the 3 segments of the default route, that is present in an ASP.NET MVC
application?
Example: http://google.com/search/label/MVC
19- ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly.
What are these 2 places?
In an ASP.NET web application that does not make use of routing, an incoming browser request
should map to a physical file. If the file does not exist, we get page not found error.
An ASP.NET web application that does make use of routing, makes use of URLs that do not have to
map to specific files in a Web site. Because the URL does not have to map to a file, you can use
URLs that are descriptive of the user's action and therefore are more easily understood by users.
21- What are the 3 things that are needed to specify a route?
1. URL Pattern - You can include placeholders in a URL pattern so that variable data can be passed
to the request handler without requiring a query string.
2. Handler - The handler can be a physical file such as an .aspx file or a controller class.
3. Name for the Route - Name is optional.
{controller}{action}/{id}
No, the above definition is not a valid route definition, because there is no literal value or delimiter
between the placeholders. Therefore, routing cannot determine where to separate the value for the
controller placeholder from the value for the action placeholder.
{resource}.axd/{*pathInfo}
This route definition, prevent requests for the Web resource files such as WebResource.axd or
ScriptResource.axd from being passed to a controller.
24- What is the difference between adding routes, to a webforms application and to an mvc
application?
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all
parameter.
controller/{action}/{*parametervalues}
1. A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by
setting the RouteExistingFiles property of the RouteCollection object to true.
2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to
prevent routing from handling certain requests.
Action Filters allow us to add pre-action and post-action behavior to controller action methods.
29- If I have multiple filters implemented, what is the order in which these filters get executed?
1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters
30- What are the different types of filters, in an asp.net mvc application?
1. Authorization filters
2. Action filters
3. Result filters
4. Exception filters
1. RequireHttpsAttribute
2. AuthorizeAttribute
Authorization filter
33- What are the levels at which filters can be applied in an asp.net mvc application?
1. Action Method
2. Controller
3. Application
Yes
Exception Filters
Yes
Result Filter
1. Razor
2. .aspx
40- What symbol would you use to denote, the start of a code block in razor views?
41- What symbol would you use to denote, the start of a code block in aspx views?
<%= %>
42- When using razor views, do you have to take any special steps to protect your asp.net mvc
application from cross site scripting (XSS) attacks?
No, by default content emitted using a @ block is automatically HTML encoded to protect from cross
site scripting (XSS) attacks.
43- When using aspx view engine, to have a consistent look and feel, across all pages of the
application, we can make use of asp.net master pages. What is asp.net master pages
equivalent, when using razor views?
To have a consistent look and feel when using razor views, we can make use of layout pages. Layout
pages, reside in the shared folder, and are named as _Layout.cshtml
Layout pages, can define sections, which can then be overriden by specific views making use of the
layout. Defining and overriding sections is optional.
Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end.
A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an
.aspx file in a Web Forms application. Routing module is responsible for mapping incoming browser
requests to particular MVC controller actions.
48- Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web
application?
Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web
application.
Use the syntax in ASP.NET MVC instead of using .net framework 4.0.