0% found this document useful (0 votes)
139 views

Core MVC

Uploaded by

R.A. Aruneash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views

Core MVC

Uploaded by

R.A. Aruneash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 135

If you're planning to attend a .NET Interview, you may also be prepared for ASP.

NET MVC
interview questions. MVC is the framework used to build Web applications for .NET and C#. In
this article, I list the top 50 MVC questions and their answers. The answers are code examples
written by authors of C# Corner

1. What is MVC (Model View Controller)?


Model–view–controller (MVC) is a software architectural pattern for implementing user
interfaces. It divides a given software application into three interconnected parts, so as
to separate internal representation of information from the way that information is
presented to or accepted from the user.

MVC is a framework for building web applications using an MVC (Model View
Controller) design:

● The Model represents the application core (for instance a list of database
records).
● The View displays the data (the database records).
● The Controller handles the input (to the database records).

The MVC model also provides full control over HTML, CSS, and JavaScript.

The MVC model defines web applications with 3 logic layers,

● The business layer (Model logic)


● The display layer (View logic)
● The input control (Controller logic)

The Model is the part of the application that handles the logic for the application data.
Often model objects retrieve data (and store data) from a database.

The View is the part of the application that handles the display of the data.

Most often the views are created from the model data.

The Controller is the part of the application that handles user interaction.

Typically controllers read data from a view, control user input, and send input data to the
model.

The MVC separation helps you manage complex applications because you can focus
on one aspect a time. For example, you can focus on the view without depending on the
business logic. It also makes it easier to test an application.

The MVC separation also simplifies group development. Different developers can work
on the view, the controller logic, and the business logic in parallel.

2. What are the advantages of MVC?

Multiple view support

Due to the separation of the model from the view, the user interface can display multiple views
of the same data at the same time.

Change Accommodation

User interfaces tend to change more frequently than business rules (different colors, fonts,
screen layouts, and levels of support for new devices such as cell phones or PDAs) because
the model does not depend on the views, adding new types of views to the system generally
does not affect the model. As a result, the scope of change is confined to the view.

SoC – Separation of Concerns


Separation of Concerns is one of the core advantages of ASP.NET MVC. The MVC framework
provides a clean separation of the UI, Business Logic, Model or Data.

More Control

The ASP.NET MVC framework provides more control over HTML, JavaScript, and CSS than the
traditional Web Forms.

Testability

ASP.NET MVC framework provides better testability of the Web Application and good support
for test driven development too.

Lightweight

ASP.NET MVC framework doesn’t use View State and thus reduces the bandwidth of the
requests to an extent.

Full features of ASP.NET

One of the key advantages of using ASP.NET MVC is that it is built on top of the ASP.NET
framework and hence most of the features of the ASP.NET like membership providers, roles, etc
can still be used.
3. Explain MVC application life cycle?

Any web application has two main execution steps, first understanding the request and
depending on the type of the request sending out an appropriate response. MVC application life
cycle is not different it has two main phases, first creating the request object and second
sending our response to the browser.

Creating the request object,

The request object creation has four major steps. The following is a detailed explanation of the
same.

Step 1 - Fill route

MVC requests are mapped to route tables which in turn specify which controller and action to be
invoked. So if the request is the first request the first thing is to fill the rout table with routes
collection. This filling of the route table happens the global.asax file.

Step 2 - Fetch route

Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData”
object which has the details of which controller and action to invoke.

Step 3 - Request context created

The “RouteData” object is used to create the “RequestContext” object.

Step 4 - Controller instance created


This request object is sent to “MvcHandler” instance to create the controller class instance.
Once the controller class object is created it calls the “Execute” method of the controller class.

Creating a Response object

This phase has two steps executing the action and finally sending the response as a result to
the view.

4. List out different return types of a controller action


method?

There are total of nine return types we can use to return results from the controller to view.

The base type of all these result types is ActionResult.

ViewResult (View)

This return type is used to return a webpage from an action method.

PartialviewResult (Partialview)
This return type is used to send a part of a view that will be rendered in another view.

RedirectResult (Redirect)

This return type is used to redirect to any other controller and action method depending on the
URL.

RedirectToRouteResult (RedirectToAction, RedirectToRoute)

This return type is used when we want to redirect to any other action method.

ContentResult (Content)

This return type is used to return HTTP content type like text/plain as the result of the action.

jsonResult (json)

This return type is used when we want to return a JSON message.

javascriptResult (javascript)

This return type is used to return JavaScript code that will run in the browser.

FileResult (File)

This return type is used to send binary output in response.


EmptyResult

This return type is used to return nothing (void) in the result.

5. What are the Filters in MVC?


In MVC, controllers define action methods and these action methods generally have a
one-to-one relationship with UI controls such as clicking a button or a link, etc. For
example, in one of our previous examples, the UserController class contained methods
UserAdd, UserDelete, etc.

But many times we would like to perform some action before or after a particular
operation. For achieving this functionality, ASP.NET MVC provides a feature to add pre
and post-action behaviors on the controller's action methods.

Types of Filters

ASP.NET MVC framework supports the following action filters,

● Action Filters

Action filters are used to implement logic that gets executed before and after a
controller action executes. We will look at Action Filters in detail in this chapter.

● Authorization Filters

Authorization filters are used to implement authentication and authorization for


controller actions.

● Result Filters
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

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 can also use exception filters to log errors.

Action filters are one of the most commonly used filters to perform additional data
processing, or manipulating the return values or canceling the execution of an action or
modifying the view structure at run time.

6. What are Action Filters in MVC?


Answer - Action Filters

Action Filters are additional attributes that can be applied to either a controller section or the
entire controller to modify the way in which action is executed. These attributes are special .NET
classes derived from System.Attribute which can be attached to classes, methods, properties, and
fields.

ASP.NET MVC provides the following action filters,

● Output Cache

This action filter caches the output of a controller action for a specified amount of time.

● Handle Error

This action filter handles errors raised when a controller action executes.
● Authorize

This action filter enables you to restrict access to a particular user or role.

Now we will see the code example to apply these filters on an example controller
ActionFilterDemoController. (ActionFilterDemoController is just used as an example. You can
use these filters on any of your controllers.)

Output Cache

Code Example

Specifies the return value to be cached for 10 seconds.

1. publicclassActionFilterDemoController: Controller
2. {
3. [HttpGet]
4. OutputCache(Duration = 10)]
5. publicstringIndex()
6. {
7. returnDateTime.Now.ToString("T");
8.
9. }
10. }

7. Explain what is routing in MVC? What are the three


segments for routing important?
Routing is a mechanism to process the incoming URL that is more descriptive and gives
the desired response. In this case, URL is not mapped to specific files or folder as was
the case of earlier days web sites.

There are two types of routing (after the introduction of ASP.NET MVC 5).

1. Convention-based routing - to define this type of routing, we call MapRoute


method and set its unique name, URL pattern and specify some default values.
2. Attribute-based routing - to define this type of routing, we specify the Route
attribute in the action method of the controller.

Routing is the URL pattern that is mapped together to a handler,routing is responsible


for incoming browser request for particular MVC controller. In other ways let us say
routing help you to define a URL structure and map the URL with controller. There are
three segments for routing that are important,

1. ControllerName
2. ActionMethodName
3. Parammeter

Code Example

ControllerName/ActionMethodName/{ParamerName} and also route map coding written


in a Global.asax file.

8. What is Route in MVC? What is Default Route in MVC?

A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as
a .aspx file in a Web Forms application. A handler can also be a class that processes the
request, such as a controller in an MVC application. To define a route, you create an instance of
the Route class by specifying the URL pattern, the handler, and optionally a name for the route.

You add the route to the application by adding the Route object to the static Routes property of
the RouteTable class. The Routesproperty is a RouteCollection object that stores all the routes
for the application.

You typically do not have to write code to add routes in an MVC application. Visual Studio
project templates for MVC include preconfigured URL routes. These are defined in the MVC
Application class, which is defined in the Global.asax file.

Route definition Example of matching URL


{controller}/{action}/{id} /Products/show/beverages
{table}/Details.aspx /Products/Details.aspx
blog/{action}/{entry} /blog/show/123
{reporttype}/{year}/{month}/{day} /sales/2008/1/5
{locale}/{action} /US/show
{language}-{country}/{action} /en-US/show
Default Route

The default ASP.NET MVC project templates add a generic route that uses the following
URL convention to break the URL for a given request into three named segments.

URL: "{controller}/{action}/{id}"

This route pattern is registered via a call to the MapRoute() extension method of
RouteCollection.

9. Mention what is the difference between Temp data,


View, and View Bag?
In ASP.NET MVC there are three ways to pass/store data between the controllers and
views.

ViewData

1. ViewData is used to pass data from controller to view.


2. It is derived from ViewDataDictionary class.
3. It is available for the current request only.
4. Requires typecasting for complex data types and checks for null values to avoid
an error.
5. If redirection occurs, then its value becomes null.

ViewBag

1. ViewBag is also used to pass data from the controller to the respective view.
2. ViewBag is a dynamic property that takes advantage of the new dynamic
features in C# 4.0
3. It is also available for the current request only.
4. If redirection occurs, then its value becomes null.
5. It doesn’t require typecasting for the complex data type.
TempData

1. TempData is derived from TempDataDictionary class


2. TempData is used to pass data from the current request to the next request
3. It keeps the information for the time of an HTTP Request. This means only from
one page to another. It helps to maintain the data when we move from one
controller to another controller or from one action to another action
4. It requires typecasting for complex data types and checks for null values to avoid
an error. Generally, it is used to store only one time messages like the error
messages and validation messages

10. What is Partial View in MVC?

A partial view is a chunk of HTML that can be safely inserted into an existing DOM. Most
commonly, partial views are used to componentize Razor views and make them easier to build
and update. Partial views can also be returned directly from controller methods. In this case, the
browser still receives text/html content but not necessarily HTML content that makes up an
entire page. As a result, if a URL that returns a partial view is directly invoked from the address
bar of a browser, an incomplete page may be displayed. This may be something like a page that
misses title, script and style sheets. However, when the same URL is invoked via a script, and
the response is used to insert HTML within the existing DOM, then the net effect for the
end-user may be much better and nicer.

Partial view is a reusable view (like a user control) which can be embedded inside another view.
For example, let’s say all the pages of your site have a standard structure with left menu,
header, and footer as in the following image,
11. Explain what is the difference between View and
Partial View?
View

● It contains the layout page.


● Before any view is rendered, viewstart page is rendered.
● A view might have markup tags like body, HTML, head, title, meta etc.
● The view is not lightweight as compare to Partial View.

Partial View

● It does not contain the layout page.


● Partial view does not verify for a viewstart.cshtml.We cannot put common code
for a partial view within the viewStart.cshtml.page.
● Partial view is designed specially to render within the view and just because of
that it does not consist any mark up.
● We can pass a regular view to the RenderPartial method.
12. What are HTML helpers in MVC?
With MVC, HTML helpers are much like traditional ASP.NET Web Form controls.

Just like web form controls in ASP.NET, HTML helpers are used to modify HTML. But
HTML helpers are more lightweight. Unlike Web Form controls, an HTML helper does
not have an event model and a view state.

In most cases, an HTML helper is just a method that returns a string.

With MVC, you can create your own helpers, or use the built in HTML helpers.

Standard HTML Helpers

HTML Links

The easiest way to render an HTML link in is to use the HTML.ActionLink() helper.With
MVC, the Html.ActionLink() does not link to a view. It creates a link to a controller action.

ASP Syntax

1. <%=Html.ActionLink("About this Website", "About")%>

The first parameter is the link text, and the second parameter is the name of the
controller action.

The Html.ActionLink() helper above, outputs the following HTML:

1. <a href="/Home/About">About this Website</a>

The Html.ActionLink() helper has several properties:

● Property Description.
● .linkText The link text (label).
● .actionName The target action.
● .routeValues The values passed to the action.
● .controllerName The target controller.
● .htmlAttributes The set of attributes to the link.
● .protocol The link protocol.
● .hostname The host name for the link.
● .fragment The anchor target for the link.

HTML Form Elements

There following HTML helpers can be used to render (modify and output) HTML form
elements:
● BeginForm()
● EndForm()
● TextArea()
● TextBox()
● CheckBox()
● RadioButton()
● ListBox()
● DropDownList()
● Hidden()
● Password()

ASP.NET Syntax C#

1. <%= Html.ValidationSummary("Create was unsuccessful. Please corre


ct the errors and try again.") %>
2. <% using (Html.BeginForm()){%>
3. <p>
4. <label for="FirstName">First Name:</label>
5. <%= Html.TextBox("FirstName") %>
6. <%= Html.ValidationMessage("FirstName", "*") %>
7. </p>
8. <p>
9. <label for="LastName">Last Name:</label>
10. <%= Html.TextBox("LastName") %>
11. <%= Html.ValidationMessage("LastName", "*") %>

12. </p>
13. <p>
14. <label for="Password">Password:</label>
15. <%= Html.Password("Password") %>
16. <%= Html.ValidationMessage("Password", "*") %>

17. </p>
18. <p>
19. <label for="Password">Confirm Password:</label>
20. <%= Html.Password("ConfirmPassword") %>
21. <%= Html.ValidationMessage("ConfirmPassword",
"*") %>
22. </p>
23. <p>
24. <label for="Profile">Profile:</label>
25. <%= Html.TextArea("Profile", new {cols=60, rows=10
})%>
26. </p>
27. <p>
28. <%= Html.CheckBox("ReceiveNewsletter") %>
29. <label for="ReceiveNewsletter" style="display:
inline">Receive Newsletter?</label>
30. </p>
31. <p>
32. <input type="submit" value="Register" />
33. </p>
34. <%}%>

13. Explain attribute based routing in MVC?


In ASP.NET MVC 5.0 we have a new attribute route,cBy using the "Route" attribute we
can define the URL structure. For example in the below code we have decorated the
"GotoAbout" action with the route attribute. The route attribute says that the
"GotoAbout" can be invoked using the URL structure "Users/about".

Hide Copy Code

1. public class HomeController: Controller


2. {
3. [Route("Users/about")]
4. publicActionResultGotoAbout()
5. {
6. return View();
7. }
8. }

14. What is TempData in MVC?

TempData is a dictionary object to store data temporarily. It is a TempDataDictionary class type


and instance property of the Controller base class.
TempData is able to keep data for the duration of a HTP request, in other words it can keep live
data between two consecutive HTTP requests. It will help us to pass the state between action
methods. TempData only works with the current and subsequent request. TempData uses a
session variable to store the data. TempData Requires type casting when used to retrieve data.

TempDataDictionary is inherited from the IDictionary<string, object>,


ICollection<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>> and
IEnumerable interfaces.

Example

1. public ActionResult FirstRequest()


2. {
3. List < string > TempDataTest = new List < string > ();
4. TempDataTest.Add("Tejas");
5. TempDataTest.Add("Jignesh");
6. TempDataTest.Add("Rakesh");
7. TempData["EmpName"] = TempDataTest;
8. return View();
9. }
10. public ActionResult ConsecutiveRequest()
11. {
12. List < string > modelData = TempData["EmpName"] as List <
string > ;
13. TempData.Keep();
14. return View(modelData);
15. }

15. What is Razor in MVC?


ASP.NET MVC has always supported the concept of "view engines" - which are the
pluggable modules that implement different template syntax options. The "default" view
engine for ASP.NET MVC uses the same .aspx/.ascx/. master file templates as
ASP.NET Web Forms. Other popular ASP.NET MVC view engines are Spart&Nhaml.

MVC 3 has introduced a new view engine called Razor.

Why is Razor?

1. Compact & Expressive.


2. Razor minimizes the number of characters and keystrokes required in a file, and
enables a fast coding workflow. Unlike most template syntaxes, you do not need
to interrupt your coding to explicitly denote server blocks within your HTML. The
parser is smart enough to infer this from your code. This enables a really
compact and expressive syntax which is clean, fast and fun to type.
3. Easy to Learn: Razor is easy to learn and enables you to quickly be productive
with a minimum of effort. We can use all your existing language and HTML skills.
4. Works with any Text Editor: Razor doesn't require a specific tool and enables you
to be productive in any plain old text editor (notepad works great).
5. Has great Intellisense:
6. Unit Testable: The new view engine implementation will support the ability to unit
test views (without requiring a controller or web-server, and can be hosted in any
unit test project - no special app-domain required).

16. Differences between Razor and ASPX View Engine in


MVC?

Razor View Engine VS ASPX View Engine

Razor View Engine ASPX View Engine (Web form view engine)

The namespace used by the Razor The namespace used by the ASPX View Engine is
View Engine is System.Web.Razor System.Web.Mvc.WebFormViewEngine

The file extensions used by the


The file extensions used by the Web Form View Engines
Razor View Engine are different
are like ASP.Net web forms. It uses the ASPX extension to
from a web form view engine. It
view the aspc extension for partial views or User Controls
uses cshtml with C# and vbhtml
or templates and master extensions for layout/master
with vb for views, partial view,
pages.
templates and layout pages.

The Razor View Engine is an


advanced view engine that was A web form view engine is the default view engine and
introduced with MVC 3.0. This is not available from the beginning of MVC
a new language but it is markup.

Razor has a syntax that is very


The web form view engine has syntax that is the same as
compact and helps us to reduce
an ASP.Net forms application.
typing.
The Razor View Engine uses @ to The ASPX/web form view engine uses "<%= %>" or "<%:
render server-side content. %>" to render server-side content.

By default all text from an @ There is a different syntax ("<%: %>") to make text HTML
expression is HTML encoded. encoded.

Razor does not require the code


block to be closed, the Razor View
Engine parses itself and it is able to A web form view engine requires the code block to be
decide at runtime which is a content closed properly otherwise it throws a runtime exception.
element and which is a code
element.

The Razor View Engine prevents


Cross-Site Scripting (XSS) attacks A web form View engine does not prevent Cross-Site
by encoding the script or HTML Scripting (XSS) attacks.
tags before rendering to the view.

Web Form view engine does not support Test Driven


The Razor Engine supports Test
Development (TDD) because it depends on the
Driven Development (TDD).
System.Web.UI.Page class to make the testing complex.

Razor uses "@* … *@" for The ASPX View Engine uses "<!--...-->" for markup and "/*
multiline comments. … */" for C# code.

There are only three transition


There are only three transition characters with the Razor
characters with the Razor View
View Engine.
Engine.

The Razor View Engine is a bit slower than the ASPX View Engine.

Conclusion

Razor provides a new view engine with a streamlined code for focused templating.
Razor's syntax is very compact and improves the readability of the markup and code.
By default, MVC supports ASPX (web forms) and Razor View Engine. MVC also
supports third-party view engines like Spark, Nhaml, NDjango, SharpDOM and so on.
ASP.NET MVC is open source.
17. What are the Main Razor Syntax Rules?
Answer

● Razor code blocks are enclosed in @{ ... }


● Inline expressions (variables and functions) start with @
● Code statements end with semicolon
● Variables are declared with the var keyword
● Strings are enclosed with quotation marks
● C# code is case sensitive
● C# files have the extension .cshtml

C# Example

1. <!-- Single statement block -->


2. @ {
3. varmyMessage = "Hello World";
4. }
5. <!-- Inline expression or variable -->
6. < p > The value of myMessage is: @myMessage < /p>
7. <!-- Multi-statement block -->
8. @ {
9. var greeting = "Welcome to our site!";
10. varweekDay = DateTime.Now.DayOfWeek;
11. vargreetingMessage = greeting + " Here in Huston it is: "
+ weekDay;
12. } < p > The greeting is: @greetingMessage < /p>

18. How do you implement Forms authentication in MVC?


Answer

Authentication is giving access to the user for a specific service by verifying his/her
identity using his/her credentials like username and password or email and password. It
assures that the correct user is authenticated or logged in for a specific service and the
right service has been provided to the specific user based on their role that is nothing
but authorization.

ASP.NET forms authentication occurs after IIS authentication is completed. You can
configure forms authentication by using forms element with in web.config file of your
application. The default attribute values for forms authentication are shown below,

1. <system.web>
2. <authenticationmode="Forms">
3. <formsloginUrl="Login.aspx" protection="All" timeout="30"
name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="
true" defaultUrl="default.aspx" cookieless="UseDeviceProfile" ena
bleCrossAppRedirects="false" />
4. </authentication>
5. </system.web>

The FormsAuthentication class creates the authentication cookie automatically when


SetAuthCookie() or RedirectFromLoginPage() methods are called. The value of
authentication cookie contains a string representation of the encrypted and signed
FormsAuthenticationTicket object.

19. Explain Areas in MVC?

Answer

From ASP.Net MVC 2.0 Microsoft provided a new feature in MVC applications, Areas. Areas are
just a way to divide or “isolate” the modules of large applications in multiple or separated MVC.
like,
When you add an area to a project, a route for the area is defined in an
AreaRegistration file. The route sends requests to the area based on the request URL.
To register routes for areas, you add code to theGlobal.asax file that can automatically
find the area routes in the AreaRegistration file.

AreaRegistration.RegisterAllAreas();

Benefits of Area in MVC

1. Allows us to organize models, views and controllers into separate functional


sections of the application, such as administration, billing, customer support and
much more.
2. Easy to integrate with other Areas created by another.
3. Easy for unit testing.

20. Explain the need of display mode in MVC?


Answer

DisplayModes give you another level of flexibility on top of the default capabilities we
saw in the last section. DisplayModes can also be used along with the previous feature
so we will simply build off of the site we just created.

Using display modes involves in 2 steps

1. We should register Display Mode with a suffix for particular browser using
“DefaultDisplayMode”e class inApplication_Start() method in the Global.asax file.
2. View name for particular browser should be appended with suffix mentioned in
first step.
1. Desktop browsers (without any suffix. e.g.: Index.cshtml, _Layout.cshtml).
2. Mobile browsers (with a suffix “Mobile”. e.g.:
Index.Mobile.cshtml,Layout.Mobile.cshtml)

If you want design different pages for different mobile device browsers (any
different browsers) and render them depending on the browser requesting. To
handle these requests you can register custom display modes. We can do that
using DisplayModeProvider.Instance.Modes.Insert(int index, IDisplayMode item)
method.

21. Explain the concept of MVC Scaffolding?

Answer

ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Visual
Studio 2013 includes pre-installed code generators for MVC and Web API projects. You add
scaffolding to your project when you want to quickly add code that interacts with data models.
Using scaffolding can reduce the amount of time to develop standard data operations in your
project.
Scaffolding consists of page templates, entity page templates, field page templates, and filter
templates. These templates are called Scaffold templates and allow you to quickly build a
functional data-driven Website.

Scaffolding Templates

Create

It creates a View that helps in creating a new record for the Model. It automatically
generates a label and input field for each property in the Model.

Delete

It creates a list of records from the model collection along with the delete link with delete
record.

Details

It generates a view that displays the label and an input field of the each property of the
Model in the MVC framework.
Edit

It creates a View with a form that helps in editing the current Model. It also generates a
form with label and field for each property of the model.

List

It generally creates a View with the help of a HTML table that lists the Models from the
Model Collection. It also generates a HTML table column for each property of the
Model.

22. What is Route Constraints in MVC?

Answer

Routing is a great feature of MVC, it provides a REST based URL that is very easy to remember
and improves page ranking in search engines.

This article is not an introduction to Routing in MVC, but we will learn a few features of routing
and by implementing them we can develop a very flexible and user-friendly application. So, let's
start without wasting valuable time.

Add constraint to URL

This is very necessary for when we want to add a specific constraint to our URL. Say, for
example we want a URL.
So, we want to set some constraint string after our host name. Fine, let's see how to implement
it.

It's very simple to implement, just open the RouteConfig.cs file and you will find the routing
definition in that. And modify the routing entry as in the following. We will see that we have
added “abc” before.

Controller name, now when we browse we need to specify the string in the URL, as in
the following:

What is Razor View Engine in MVC?

Answer

ASP.NET MVC has always supported the concept of "view engines" that are the pluggable
modules that implement various template syntax options. The "default" view engine for
ASP.NET MVC uses the same .aspx/.ascx/.master file templates as ASP.NET Web Forms. In
this article I go through the Razor View Engine to create a view of an application. "Razor" was in
development beginning in June 2010 and was released for Microsoft Visual Studio in January
2011.
Razor is not a new programming language itself, but uses C# syntax for embedding code in a
page without the ASP.NET delimiters: <%= %>. It is a simple-syntax view engine and was
released as part of ASP.NET MVC 3. The Razor file extension is "cshtml" for the C# language. It
supports TDD (Test Driven Development) because it does not depend on the
System.Web.UI.Page class.

24. What is Output Caching in MVC?


Answer

The main purpose of using Output Caching is to dramatically improve the performance
of an ASP.NET MVC Application. It enables us to cache the content returned by any
controller method so that the same content does not need to be generated each time
the same controller method is invoked. Output Caching has huge advantages, such as it
reduces server round trips, reduces database server round trips, reduces network traffic
etc.

Keep the following in mind,

● Avoid caching contents that are unique per user.


● Avoid caching contents that are accessed rarely.
● Use caching for contents that are accessed frequently.

Let's take an example. My MVC application displays a list of database records on the
view page so by default each time the user invokes the controller method to see
records, the application loops through the entire process and executes the database
query. And this can actually decrease the application performance. So, we can
advantage of the "Output Caching" that avoids executing database queries each time
the user invokes the controller method. Here the view page is retrieved from the cache
instead of invoking the controller method and doing redundant work.

Cached Content Locations

In the above paragraph I said, in Output Caching the view page is retrieved from the
cache, so where is the content cached/stored?

Please note, there is no guarantee that content will be cached for the amount of time
that we specify. When memory resources become low, the cache starts evicting content
automatically.

OutputCache label has a "Location" attribute and it is fully controllable. Its default value
is "Any", however there are the following locations available; as of now, we can use any
one.
1. Any
2. Client
3. Downstream
4. Server
5. None
6. ServerAndClient

With "Any", the output cache is stored on the server where the request was processed.
The recommended store cache is always on the server very carefully. You will learn
about some security related tips in the following "Don't use Output Cache".

25. What is Bundling and Minification in MVC?

Answer

Bundling and minification are two new techniques introduced to improve request load time. It
improves load time by reducing the number of requests to the server and reducing the size of
requested assets (such as CSS and JavaScript).

Bundling

It lets us combine multiple JavaScript (.js) files or multiple cascading style sheet (.css) files so
that they can be downloaded as a unit, rather than making individual HTTP requests.

Minification

It squeezes out whitespace and performs other types of compression to make the downloaded
files as small as possible. At runtime, the process identifies the user agent, for example IE,
Mozilla, etc. and then removes whatever is specific to Mozilla when the request comes from IE.
26. What is Validation Summary in MVC?

Answer

The ValidationSummary helper method generates an unordered list (ul element) of validation
messages that are in the ModelStateDictionary object.

The ValidationSummary can be used to display all the error messages for all the fields. It can
also be used to display custom error messages. The following figure shows how
ValidationSummary displays the error messages.

ValidationSummary() Signature

MvcHtmlStringValidateMessage(bool excludePropertyErrors, string message, object


htmlAttributes)

Display field level error messages using ValidationSummary

By default, ValidationSummary filters out field level error messages. If you want to display field
level error messages as a summary then specify excludePropertyErrors = false.
Example - ValidationSummary to display field errors

@Html.ValidationSummary(false, "", new { @class = "text-danger" })

So now, the following Edit view will display error messages as a summary at the top. Please
make sure that you don't have a ValidationMessageFor method for each of the fields.

27. What is Database First Approach in MVC using Entity


Framework?
Answer

Database First Approach is an alternative to the Code First and Model First approaches
to the Entity Data Model which creates model codes (classes,properties, DbContextetc)
from the database in the project and that classes behaves as the link between database
and controller.

There are the following approach which is used to connect with database to application.

● Database First
● Model First
● Code First
Database first is nothing but only a approach to create web application where database is
available first and can interact with the database. In this database, database is created first and
after that we manage the code. The Entity Framework is able to generate a business model
based on the tables and columns in a relational database.

28. What are the Folders in MVC application solutions?

Answer - Understanding the folders

When you create a project a folder structure gets created by default under the name of your
project which can be seen in solution explorer. Below i will give you a brief explanation of what
these folders are for.

Model

This folder contains classes that is used to provide data. These classes can contain data that is
retrived from the database or data inserted in the form by the user to update the database.

Controllers

These are the classes which will perform the action invoked by the user. These classes contains
methods known as "Actions" which responds to the user action accordingly.

Views
These are simple pages which uses the model class data to populate the HTML controls and
renders it to the client browser.

App_Start

Contains Classes such as FilterConfig, RoutesConfig, WebApiConfig. As of now we need to


understand the RouteConfig class. This class contains the default format of the url that should
be supplied in the browser to navigate to a specified page.

29. What is difference between MVC and Web Forms?

Answer - ASP.Net MVC / Web Forms difference

The following are some difference.

ASP.Net MVC ASP.Net Web Forms

View and logic are separate, it has separation of No separation of concerns; Views are
concerns theory. MVC 3 onwards has .aspx page as tightly coupled with logic (.aspx.cs /.vb
.cshtml. file).

Introduced concept of routing for route based URL. File-based routing .Redirection is based
Routing is declared in Global.asax for example. on pages.

Support Razor syntax as well as .aspx Support web forms syntax only.

State management handled via Tempdata, ViewBag,


and View Data. Since the controller and view are not State management handled via View
dependent and also since there is no view state State. Large viewstate, in other words
concept in ASP.NET, MVC keeps the pages increase in page size.
lightweight.

Partial Views User Controls


HTML Helpers Server Controls

Multiple pages can have the same controller to Each page has its own code, in other
satisfy their requirements. A controller may have words direct dependency on code. For
multiple Actions (method name inside the controller example Sachin.aspx is dependent on
class). Sachin.aspx.cs (code behind) file.

Unit Testing is quite easier than ASP.Net Web forms Direct dependency, tight coupling raises
Since a web form and code are separate files. issues in testing.

layouts Master pages

30. What are the methods of handling an Error in MVC?


Answer

Exception handling may be required in any application, whether it is a web application


or a Windows Forms application.

ASP.Net MVC has an attribute called "HandleError" that provides built-in exception
filters. The HandleError attribute in ASP.NET MVC can be applied over the action
method as well as Controller or at the global level. The HandleError attribute is the
default implementation of IExceptionFilter. When we create a MVC application, the
HandleError attribute is added within the Global.asax.cs file and registered in the
Application_Start event.

1. public static void RegisterGlobalFilters(GlobalFilterCollection f


ilters)
2. {
3. filters.Add(new HandleErrorAttribute());
4. }
5. protected void Application_Start()
6. {
7. AreaRegistration.RegisterAllAreas();
8. RegisterGlobalFilters(GlobalFilters.Filters);
9. RegisterRoutes(RouteTable.Routes);
10. }

Important properties of HandleError attribute


The HandleError Error attribute has a couple for properties that are very useful in
handling the exception.

ExceptionType

Type of exception to be catch. If this property is not specified then the HandleError filter
handles all exceptions.

View

Name of the view page for displaying the exception information.

Master

Master View for displaying the exception.

Order

Order in which the action filters are executed. The Order property has an integer value
and it specifies the priority from 1 to any positive integer value. 1 means highest priority
and the greater the value of the integer is, the lower is the priority of the filter.

AllowMultiple

It indicates whether more than one instance of the error filter attribute can be specified.

Example

1. [HandleError(View = "Error")]
2. public class HomeController: Controller
3. {
4. public ActionResult Index()
5. {
6. ViewBag.Message = "Welcome to ASP.NET MVC!";
7. int u = Convert.ToInt32(""); // Error line
8. return View();
9. }
10. }

HandleError Attribute at Action Method Level,

1. [HandleError(View = "Error")]
2. public ActionResult Index()
3. {
4. ViewBag.Message = "Welcome to ASP.NET MVC!";
5. int u = Convert.ToInt32(""); // Error line
6. return View();
7. }

31. How can we pass the data From Controller To View In


MVC?
Answer

There are three options in Model View Controller (MVC) for passing data from controller
to view. This article attempts to explain the differences among ViewData, ViewBag and
TempData with examples. ViewData and ViewBag are similar and TempData performs
additional responsibility. The following are the key points on those three objects.

ViewData

● The ViewData is used to move data from controller to view.


● The ViewData is a dictionary of objects that are derived from the
"ViewDataDictionary" class and it will be accessible using strings as keys.
● ViewData contains a null value when redirection occurs.
● ViewData requires typecasting for complex data types.

ViewBag

● ViewBag is just a dynamic wrapper around ViewData and exists only in ASP.NET
MVC 3. ViewBag is a dynamic property that takes advantage of the new dynamic
features in C# 4.0.
● ViewBag doesn't require typecasting for complex data types.
● ViewBag also contain a null value when redirection occurs.
TempData

● ViewData moves data from controller to view.


● Use TempData when you need data to be available for the next request, only. In
the next request, it will be there but will be gone after that.
● TempData is used to pass data from the current request to the subsequent
request, in other words in case of redirection. That means the value of TempData
will not be null.

32. What is Scaffolding in MVC?


Answer

Scaffolding is a code generation framework for ASP.NET Web applications. Visual


Studio 2013 includes pre-installed code generators for MVC and Web API projects. You
add scaffolding to your project when you want to quickly add code that interacts with
data models. Using scaffolding can reduce the amount of time to develop standard data
operations in your project.

Prerequisites

To use ASP.NET Scaffolding, you must have,

● Microsoft Visual Studio 2013


● Web Developer Tools (part of default Visual Studio 2013 installation)
● ASP.NET Web Frameworks and Tools 2013 (part of default Visual Studio 2013
installation)

What are the Advantages of using Scaffolding ?

● Minimal or no code to create a data-driven Web applications.


● Quick development time.
● Pages that are fully functional and include display, insert, edit, delete, sorting,
and paging functionalities.
● Built-in data validation that is based on the database schema.
● Filters that are created for each foreign key or Boolean fields.
33. What is ViewStart?
Answer

Razor View Engine introduced a new layout named _ViewStart which is applied on all
view automatically. Razor View Engine firstly executes the _ViewStart and then start
rendering the other view and merges them.

Example of Viewstart

1. @ {
2. Layout = "~/Views/Shared/_v1.cshtml";
3. } < !DOCTYPE html >
4. < html >
5. < head >
6. < meta name = "viewport"
7. content = "width=device-width" / >
8. < title > ViewStart < /title> < /head> < body >
9. < /body> < /html>

34. What is JsonResultType in MVC?


Answer

Action methods on controllers return JsonResult (JavaScript Object Notation result) that
can be used in an AJAX application. This class is inherited from the "ActionResult"
abstract class. Here Json is provided one argument which must be serializable. The
JSON result object that serializes the specified object to JSON format.

1. public JsonResult JsonResultTest()


2. {
3. return Json("Hello My Friend!");
4. }

35. What is TempData?


Answer - Tempdata

● TempData is a dictionary object derived from the TempDataDictionary class.


● TempData is used to pass data from the current request to a subsequent request,
in other words in the case of redirection.
● The life of a TempData is very short and it retains its value for a short period of
time.
● It requires typecasting for complex data type as I’ve used in my example:
● @foreach (var item in
(List<MVCSample.Models.EmpRegistration>)TempData["EmployeeRegistration"]
)
● You can retain its value using the Keep method for subsequent requests.

36. How to use ViewBag?


Answer

ViewBag is dynamic property that takes advantage of new dynamic features in C# 4.0.
It's also used to pass data from a controller to a view. In short, The ViewBag property is
simply a wrapper around the ViewData that exposes the ViewData dictionary as a
dynamic object. Now create an action method "StudentSummary" in the
"DisplayDataController" controller that stores a Student class object in ViewBag.

1. public ActionResult StudentSummary()


2. {
3. var student = new Student()
4. {
5. Name = "Sandeep Singh Shekhawat",
6. Age = 24,
7. City = "Jaipur"
8. };
9. ViewBag.Student = student;
10. return View();
11. }

Thereafter create a view StudentSummary ("StudentSummary.cshtml") that shows


student object data. ViewBag does not require typecasting for complex data type so you
can directly access the data from ViewBag.

1. @ {
2. ViewBag.Title = "Student Summary";
3. var student = ViewBag.Student;
4. }
5. < table >
6. < tr >
7. < th > Name < /th> < th > Age < /th> < th > City < /th> < /tr
> < tr >
8. < td > @student.Name < /td> < td > @student.Age < /td> < td >
@student.City < /td> < /tr>
9. < /table>

Here we used one more thing, "ViewBag.Title", that shows the title of the page.

37. What are the Difference between ViewBag&ViewData?


Answer - Difference between ViewBag&ViewData?

● ViewData is a dictionary of objects that is derived from ViewDataDictionary class


and accessible using strings as keys.
● ViewBag is a dynamic property that takes advantage of the new dynamic
features in C# 4.0.
● ViewData requires typecasting for complex data type and check for null values to
avoid error.
● ViewBag doesn't require typecasting for complex data type.
● Calling of ViewBag is:

ViewBag.Name = "Yogesh";
Calling of ViewDatais :

ViewData["Name"] = "yogesh";

38. What is Data Annotation Validator Attributes in MVC?


Answer - Using the Data Annotation Validator Attributes

DataAnnotation plays a vital role in added validation to properties while designing the
model itself. This validation can be added for both the client side and the server side.

You understand that decorating the properties in a model with an Attribute can make
that property eligible for Validation.

Some of the DataAnnotation used for validation are given below,


1. Required

Specify a property as required.

1. [Required(ErrorMessage="CustomerName is mandatory")]

2. RegularExpression

Specifies the regular expression to validate the value of the property.

1. [RegularExpression("[a-z]", ErrorMessage = "Invalid character")]

3. Range

Specifies the Range of values between which the property values are checked.

1. [Range(1000,10000,ErrorMessage="Range should be between 1k & 10k")]

4. StringLength

Specifies the Min & Max length for a string property.

1. [StringLength(50, MinimumLength = 5, ErrorMessage = "Minimum char is 5


and maximum char is 10")]
5. MaxLength

Specifies the Max length for the property value.

1. [MaxLength(10,ErrorMessage="Customer Code is exceeding")]

6. MinLength

It is used to check for minimum length.

1. [MinLength(5, ErrorMessage = "Customer Code is too small")]

39. How can we done Custom Error Page in MVC?


Answer

The HandleErrorAttribute allows you to use a custom page for this error. First you need
to update your web.config file to allow your application to handle custom errors.

1. <system.web>
2. <customErrors mode="On">
3. </system.web>

Then, your action method needs to be marked with the atttribute.

1. [HandleError]
2. public class HomeController: Controller
3. {
4. [HandleError]
5. publicActionResultThrowException()
6. {
7. throw new ApplicationException();
8. }
9. }

By calling the ThrowException action, this would then redirect the user to the default
error page. In our case though, we want to use a custom error page and redirect the
user there instead.So, let's create our new custom view page.

Next, we simply need to update the HandleErrorAttribute on the action method.

1. [HandleError]
2. public class HomeController: Controller
3. {
4. [HandleError(View = "CustomErrorView")]
5. publicActionResultThrowException()
6. {
7. throw new ApplicationException();
8. }
9. }

40. Server Side Validation in MVC?


Answer

The ASP.NET MVC Framework validates any data passed to the controller action that is
executing, It populates a ModelState object with any validation failures that it finds and
passes that object to the controller. Then the controller actions can query the
ModelState to discover whether the request is valid and react accordingly.

I will use two approaches in this article to validate a model data. One is to manually add
an error to the ModelState object and another uses the Data Annotation API to validate
the model data.

Approach 1 - Manually Add Error to ModelState object

I create a User class under the Models folder. The User class has two properties
"Name" and "Email". The "Name" field has required field validations while the "Email"
field has Email validation. So let's see the procedure to implement the validation. Create
the User Model as in the following,

1. namespace ServerValidation.Models
2. {
3. public class User
4. {
5. public string Name
6. {
7. get;
8. set;
9. }
10. public string Email
11. {
12. get;
13. set;
14. }
15. }
16. }

After that I create a controller action in User Controller (UserController.cs under


Controllers folder). That action method has logic for the required validation for Name
and Email validation on the Email field. I add an error message on ModelState with a
key and that message will be shown on the view whenever the data is not to be
validated in the model.

1. using System.Text.RegularExpressions;
2. using System.Web.Mvc;
3. namespace ServerValidation.Controllers
4. {
5. public class UserController: Controller
6. {
7. public ActionResult Index()
8. {
9. return View();
10. }
11. [HttpPost]
12. public ActionResult Index(ServerValidation.Models.User
model)
13. {
14.
15. if (string.IsNullOrEmpty(model.Name))
16. {
17. ModelState.AddModelError("Name", "Name is requ
ired");
18. }
19. if (!string.IsNullOrEmpty(model.Email))
20. {
21. string emailRegex = @ "^([a-zA-Z0-9_\-\.]+)@((
\[[0-9]{1,3}" +
22. @ "\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-
9\-]+\" +
23. @ ".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
24. Regex re = new Regex(emailRegex);
25. if (!re.IsMatch(model.Email))
26. {
27. ModelState.AddModelError("Email", "Email i
s not valid");
28. }
29. } else {
30. ModelState.AddModelError("Email", "Email is re
quired");
31. }
32. if (ModelState.IsValid)
33. {
34. ViewBag.Name = model.Name;
35. ViewBag.Email = model.Email;
36. }
37. return View(model);
38. }
39. }
40. }

Thereafter I create a view (Index.cshtml) for the user input under the User folder.

1. @model ServerValidation.Models.User
2. @ {
3. ViewBag.Title = "Index";
4. }
5. @using(Html.BeginForm())
6. {
7. if (@ViewData.ModelState.IsValid)
8. {
9. if (@ViewBag.Name != null)
10. { < b >
11. Name: @ViewBag.Name < br / >
12. Email: @ViewBag.Email < /b>
13. }
14. } < fieldset >
15. < legend > User < /legend> < div class = "editor-labe
l" >
16. @Html.LabelFor(model => model.Name) < /div> < div clas
s = "editor-field" >
17. @Html.EditorFor(model => model.Name)
18. @if(!ViewData.ModelState.IsValid)
19. {
20. < span class = "field-validation-error" > @ViewData.ModelState
["Name"].Errors[0].ErrorMessage < /span>
21.
22. }
23. < /div> < div class = "editor-label" >
24.
25. @Html.LabelFor(model => model.Email) < /div> < div cla
ss = "editor-field" >
26. @Html.EditorFor(model => model.Email)
27. @if(!ViewData.ModelState.IsValid)
28. {
29. < span class = "field-validation-error" > @ViewData.ModelState
["Email"].Errors[0].ErrorMessage < /span>
30. }
31. < /div> < p >
32. < input type = "submit"
33. value = "Create" / >
34. < /p> < /fieldset>
35. }

41. What is the use of remote validation in MVC?


Answer

Remote validation is the process where we validate specific data posting data to a
server without posting the entire form data to the server. Let's see an actual scenario, in
one of my projects I had a requirement to validate an email address, whetehr it already
exists in the database. Remote validation was useful for that; without posting all the
data we can validate only the email address supplied by the user.

Practical Explanation

Let's create a MVC project and name it accordingly, for me its


“TestingRemoteValidation”. Once the project is created let's create a model named
UserModel that will look like:

1. public class UserModel


2. {
3. [Required]
4. public string UserName
5. {
6. get;
7. set;
8. }
9. [Remote("CheckExistingEmail", "Home", ErrorMessage = "Email a
lready exists!")]
10. public string UserEmailAddress
11. {
12. get;
13. set;
14. }
15. }

Let's get some understanding of the remote attribute used, so the very first parameter
“CheckExistingEmail” is the the name of the action. The second parameter “Home” is
referred to as controller so to validate the input for the UserEmailAddress the
“CheckExistingEmail” action of the “Home” controller is called and the third parameter is
the error message. Let's implement the “CheckExistingEmail” action result in our home
controller.

1. public ActionResult CheckExistingEmail(string UserEmailAddress)


2. {
3. bool ifEmailExist = false;
4. try
5. {
6. ifEmailExist = UserEmailAddress.Equals("mukeshknayak@gmai
l.com") ? true : false;
7. return Json(!ifEmailExist, JsonRequestBehavior.AllowGet);

8. } catch (Exception ex)


9. {
10. return Json(false, JsonRequestBehavior.AllowGet);
11. }
12. }

42. What are the Exception filters in MVC?


Answer
Exception are part and parcel of an application. They are a boon and a ban for an
application too. Isn't it? This would be controversial, for developers it helps them track
minor and major defects in an application and sometimes they are frustrating when it
lets users land on the Yellow screen of death each time. This would make the users
mundane to the application. Thus to avoid this, developers handle the exceptions. But
still sometimes there are a few unhandled exceptions.

Now what is to be done for them? MVC provides us with built-in "Exception Filters"
about which we will explain here.

cc: Google

Let's start!

A Yellow screen of Death can be said is as a wardrobe malfunction of our application.

Get Started

Exception filters run when some of the exceptions are unhandled and thrown from an
invoked action. The reason for the exception can be anything and so is the source of
the exception.

Creating an Exception Filter

Custom Exception Filters must implement the builtinIExceptionFilter interface. The


interface looks as in the following,

1. public interface IExceptionFilter


2. {
3. void OnException(ExceptionContext filterContext)
4. }

Whenever an unhandled exception is encountered, the OnException method gets


invoked. The parameter as we can see, ExceptionContext is derived from the
ControllerContext and has a number of built-in properties that can be used to get the
information about the request causing the exception. Their property's
ExceptionContextpassess are shown in the following table:

Name Type Detail


Result ActionResult The result returned by the action being invoked.
The unhandled exceptions caused from the actions in
Exception Exception
the applications.
This is a very handy property that returns a bool value
ExceptionHandled BOOL (true/false) based on if the exception is handled by any
of the filters in the applicaiton or not.

The exception being thrown from the action is detailed by the Exception property and
once handled (if), then the property ExceptionHandled can be toggled, so that the other
filters would know if the exception has been already handled and cancel the other filter
requests to handle. The problem is that if the exceptions are not handled, then the
default MVC behavior shows the dreaded yellow screen of death. To the users, that
makes a very impression on the users and more importantly, it exposes the application's
handy and secure information to the outside world that may have hackers and then the
application gets into the road to hell. Thus, the exceptions need to be dealt with very
carefully. Let's show one small custom exception filter. This filter can be stored inside
the Filters folder in the web project of the solution. Let's add a file/class called
CustomExceptionFilter.cs.

1. public class CustomExceptionFilter: FilterAttribute,


2. IExceptionFilter
3. {
4. public void OnException(ExceptionContext filterContext)
5. {
6. if (!filterContext.ExceptionHandled && filterContext.
Exception is NullReferenceException)
7. {
8. filterContext.Result = new RedirectResult("custom
ErrorPage.html");
9. filterContext.ExceptionHandled = true;
10. }
11. }
12. }
43. What is MVC HTML- Helpers and its Methods?
Answer

Helper methods are used to render HTML in the view. Helper methods generates HTML
output that is part of the view. They provide an advantage over using the HTML
elements since they can be reused across the views and also requires less coding.
There are several builtin helper methods that are used to generate the HTML for some
commonly used HTML elements, like form, checkbox, dropdownlist etc. Also we can
create our own helper methods to generate custom HTML. First we will see how to use
the builtin helper methods and then we will see how to create custom helper methods.

Standard HtmlHelper methods

Some of the standard helper methods are,

● ActionLink: Renders an anchor.


● BeginForm: Renders HTML form tag
● CheckBox: Renders check box.
● DropDownList: Renders drop-down list.
● Hidden: Renders hidden field
● ListBox: Renders list box.
● Password: Renders TextBox for password input
● RadioButton: Renders radio button.
● TextArea: Renders text area.
● TextBox: Renders text box.

44. Define Controller in MVC?

Answer

The controller provides model data to the view, and interprets user actions such as button clicks.
The controller depends on the view and the model. In some cases, the controller and the view
are the same object.
The Controllers Folder

The Controllers Folder contains the controller classes responsible for handling user input and
responses. MVC requires the name of all controllers to end with "Controller".

In our example, Visual Web Developer has created the following files: HomeController.cs (for
the Home and About pages) and AccountController.cs (For the Log On pages):

45. Explain Model in MVC?

Answer

The model represents the data, and does nothing else. The model does NOT depend on the
controller or the view. The MVC Model contains all application logic (business logic, validation
logic, and data access logic), except pure view and controller logic. With MVC, models both hold
and manipulate application data.

The Models Folde

The Models Folder contains the classes that represent the application model.

Visual Web Developer automatically creates an AccountModels.cs file that contains the models
for application security.

46. Explain View in MVC?

Answer

A view is responsible for displaying all of, or a portion of, data for users. In simple terms,
whatever we see on the output screen is a view.

The Views Folder

The Views folder stores the files (HTML files) related to the display of the application (the user
interfaces). These files may have the extensions html, asp, aspx, cshtml, and vbhtml, depending
on the language content.

The Views folder contains one folder for each controller. Visual Web Developer has created an
Account folder, a Home folder, and a Shared folder (inside the Views folder). The Account folder
contains pages for registering and logging in to user accounts. The Home folder is used for
storing application pages like the home page and the about page. The Shared folder is used to
store views shared between controllers (master pages and layout pages).
47. What is Attribute Routing in MVC?
Answer

A route attribute is defined on top of an action method. The following is the example of a
Route Attribute in which routing is defined where the action method is defined.

In the following example, I am defining the route attribute on top of the action method

1. public class HomeController: Controller


2. {
3. //URL: /Mvctest
4. [Route(“Mvctest”)]
5. public ActionResult Index()
6. ViewBag.Message = "Welcome to ASP.NET MVC!";
7. return View();
8. }
9. }

Attribute Routing with Optional Parameter

We can also define an optional parameter in the URL pattern by defining a mark (“?") to
the route parameter. We can also define the default value by using parameter=value.

1. public class HomeController: Controller


2. {
3. // Optional URI Parameter
4. // URL: /Mvctest/
5. // URL: /Mvctest/0023654
6. [Route(“Mvctest /
7. {
8. customerName ?
9. }”)]
10. public ActionResult OtherTest(string customerName)
11. ViewBag.Message = "Welcome to ASP.NET MVC!";
12. return View();
13. }
14. // Optional URI Parameter with default value
15. // URL: /Mvctest/
16. // URL: /Mvctest/0023654
17. [Route(“Mvctest /
18. {
19. customerName = 0036952
20. }”)]
21. public ActionResult OtherTest(string customerName)
22. {
23. ViewBag.Message = "Welcome to ASP.NET MVC!";
24. return View();
25. }
26. }

48. Explain RenderSection in MVC?


Answer

RenderSection() is a method of the WebPageBase class. Scott wrote at one point, The
first parameter to the "RenderSection()" helper method specifies the name of the
section we want to render at that location in the layout template. The second parameter
is optional, and allows us to define whether the section we are rendering is required or
not. If a section is "required", then Razor will throw an error at runtime if that section is
not implemented within a view template that is based on the layout file (that can make it
easier to track down content errors). It returns the HTML content to render.

1. <div id="body">
2. @RenderSection("featured", required: false)
3. <section class="content-wrapper main-content clear-fix">
4. @RenderBody()
5. </section>
6. </div>

49. What is GET and POST Actions Types?

Answer

GET

GET is used to request data from a specified resource. With all the GET request we pass the
URL which is compulsory, however it can take the following overloads.

.get(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ).done/.fail

POST

POST is used to submit data to be processed to a specified resource. With all the POST
requests we pass the URL which is compulsory and the data, however it can take the following
overloads.

.post(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

50. What's new in MVC 6?

Answer
In MVC 6 Microsoft removed the dependency of System.Web.Dll from MVC6 because it's so
expensive that typically it consume 30k of memory per request and response, whereas now
MVC 6 only requires 2k of memory per request and the response is a very small memory
consumtion.

The advantage of using the cloud-optimized framework is that we can include a copy of the
mono CLR with your website. For the sake of one website we do not need to upgrade the .NET
version on the entire machine. A different version of the CLR for a different website running side
by side.

MVC 6 is a part of ASP.NET 5 that has been designed for cloud-optimized applications. The
runtime automatically picks the correct version of the library when our MVC application is
deployed to the cloud.

The Core CLR is also supposed to be tuned with a high resource-efficient optimization.

Microsoft has made many MVC, Web API, WebPage and SignalLrpeices we call MVC 6.
Most of the problems are solved using the Roslyn Compiler. In ASP.NET vNext uses the Roslyn
Compiler. Using the Roslyn Compiler we do not need to compile the application, it automatically
compiles the application code. You will edit a code file and can then see the changes by
refreshing the browser without stopping or rebuilding the project.

Run on hosts other than IIS

Where we use MVC5 we can host it on an IIS server and we can also run it on top of an ASP.
NET Pipeline, on the other hand MVC 6 has a feature that makes it better and that feature is
itself hosted on an IIS server and a self-user pipeline.

Environment based configuration system

The configuration system provides an environment to easily deploy the application on the cloud.
Our application works just like a configuration provider. It helps to retrieve the value from the
various configuration sources like XML file.

MVC 6 includes a new environment-based configuration system. Unlike something else it


depends on just the Web.Config file in the previous version.

Dependency injection

Using the IServiceProvider interface we can easily add our own dependency injection container.
We can replace the default implementation with our own container.

Supports OWIN

We have complete control over the composable pipeline in MVC 6 applications. MVC 6 supports
the OWIN abstraction.
What is an ORM, and why would you use one instead of plain old
ADO.NET?
Hide answer
An ORM is an object relational mapping framework. Such a framework can help to
reduce the amount of handwritten code in a typical web application. ORM can be used
when there are no extreme requirements for performance in an application, but there
are some frameworks (e.g., Dapper) which can be used even in high-load systems.

[ASP.NET Core MVC] You have a CategoriesController and an Add action with the
next signature looking like this:
[HttpPost]
public IActionResult Add(NewCategoryModel model)
You have to explicitly specify that the parameter model should be extracted from a
request body. How would you achieve that?
Hide answer
Add [FromBody] like so:
[HttpPost]
public IActionResult Add([FromBody]NewCategoryModel model)

[ASP.NET MVC 5] Is that OK to place a log.txt file in the ~/bin/ folder of


an ASP.NET MVC application? Will it affect the app?
Hide answer
It is not a good idea to put log files in the bin folder of an application, because every
change will cause a pool restart. You will face performance problems and unless you
already know this, it will be difficult to track down the reason.

[ASP.NET MVC 5] What basic folders do we have in an ASP.NET


project without Areas? What are they for? What subfolders do they
have (if applicable)? Which folders are publicly accessible?
Hide answer
● App_Data can be used to store some application’s data.
● App_Start contains configuration classes: RouteConfig, BundleConfig, etc.
● Content is a publicly accessible folder for static files, such as CSS files, images, etc.,
but not scripts.
● Controllers is a default folder for application controllers.
● Scripts is a publicly accessible folder for JavaScript files.
● Views: The folder contains a folder for every controller, plus a special
folder Shared for views used by multiple views/controllers. For example, if we have a
controller called HomeController, we will have a Home subfolder here with all the
views related to HomeController.

[ASP.NET Core MVC] What basic folders do we have in an ASP.NET


Core project using the MVC template without Areas? What are they
for? What subfolders do they have (if applicable)? Which folders are
publicly accessible?
Hide answer
● wwwroot: The root folder of a site, publicly accessible, contains subfolders for static
files (CSS, images, JS, etc.).
● Controllers: A default folder for application controllers
● Views: The folder contains a folder for every controller, plus a special
folder Shared for views used by multiple views/controllers. For example, if we have a
controller called HomeController, we will have a Home subfolder here with all the
views related to HomeController.

What does MVC mean?


Hide answer
Model-View-Controller is an architectural pattern.The main idea is to separate business
logic from an application’s UI.
Application logic is located in controllers. Views are responsible for the rendering of the
appropriate UI. Models are usually used to transfer data back and forth between
controllers and views. Some people also use them for wrapping business logic, sharing
the model with an ORM tool. But it’s better to use the model only for transfering data (as
a data transfer object) and as a validation contract (by marking the model’s properties
with data annotation attributes).

You have a controller CategoriesController with actions ShowAll, Add,


and Delete. You’ve got several requirements related to application
URLs:

URL Action Method


ShowAl
~/v2/Categories l GET
~/v2/Categories/Add Add POST
DELET
~/v2/Categories/Delete Delete E
What is the easiest way to achieve that?
Hide answer
In ASP.NET MVC 5:
Use a custom route and attributes on action methods to restrict HTTP methods.

Step 1: We need to add a custom route to RoutesCollection (usually


in ~/App_Start/RoutesConfig) before the default one:
routes.MapRoute(
name: "v2",
url: "v2/{controller}/{action}",
defaults: new { action = "ShowAll" }
);
Step 2: To restrict HTTP methods for actions, we need to
mark CategoriesController’s methods with the attributes [HttpGet], [HttpPost],
and [HttpDelete] according to our requirements.

In ASP.NET Core MVC:


There are three ways to fulfill these requirements.

Option #1: Add a custom global route and attributes on action


methods to restrict HTTP methods.

Step 1: We need to add a custom global route (usually in Startup.cs) before the
default one:
routes.MapRoute(
name: "v2",
template: "v2/{controller}/{action=ShowAll}"
);

Step 2: To restrict HTTP methods for actions, we need to


mark CategoriesController’s methods with the attributes [HttpGet], [HttpPost],
and [HttpDelete] according to our requirements.
This is a good approach for applications without specific requirements for a URL
scheme.
Option #2: Configure routes at the action level.

Steps:

1. Mark actions with attributes to restrict allowed HTTP methods.

2. Specify route templates via attributes:

[HttpGet]
[Route("v2/[controller]")]
public IActionResult ShowAll()
{
return View();
}

[HttpPost]
[Route("v2/[controller]/[action]")]
public IActionResult Add()
{
return View();
}

This is a good decision if you have specific requirements for a URL scheme, e.g., a
REST API.

Option #3: Configure a base route on a controller level and relative routes on an action
level.
Steps:

1. Specify a basic controller route template with an attribute.

2. Mark actions with attributes to restrict allowed HTTP methods.

3. Specify relative route templates via attributes:

[Route("v2/[controller]")]
public class CategoriesController : Controller
{
[HttpGet]
[Route("")]
public IActionResult ShowAll()
{
return View();
}

[HttpPost]
[Route("[action]")]
public IActionResult Add()
{
return View();
}
// ...

This is also a good decision if you have specific requirements for a URL scheme. In fact, it can
be a better option than the previous one if you always have a constant string or a controller
name as a prefix for your routes.

By default, you have the master page in your


application ~/Views/Shared/_Layout.cshtml and you’ve created a new
one ~/Views/Shared/_LayoutV2.cshtml. How do you apply the new
master page to the whole application, except pages with a non-default
layout?
Hide answer
In both ASP.NET MVC 5 and ASP.NET Core MVC, you have to adjust the
file ~/Views/_ViewStart.cshtml.
In ASP.NET MVC 5:
@{
Layout = "~/Views/Shared/_LayoutV2.cshtml";
}

In ASP.NET Core MVC:


@{
Layout = "_LayoutV2";
}
What is the recommended approach for ASP.NET MVC to
globally intercept exceptions? What other functionality can
be implemented with the approach?
You can create a custom exception filter to intercept and log unhandled exceptions.

In ASP.NET MVC 5:
To intercept exceptions globally, the filter should be registered
in GlobalFilterCollection (usually in ~/App_Start/FilterConfig). Authentication,
authorization, custom action filters, logging, and action result transformation can be
done with the same approach.

In ASP.NET Core MVC:


To intercept exceptions globally, the filter should be registered
in Startup.ConfigureServices() as shown below:
services.AddMvc(options => { options.Filters.Add(new
ApiExceptionFilter()); });
Authorization, custom action filters (sync and async), and action result transformation
can be done with the same approach.

What are the advantages of using IoC containers in an


application?
Hide answer
The main advantages are:

● The lifetime of every object can be managed externally.

● Objects are not responsible for creating services and providing dependencies.

● Changes to a dependency list won’t affect an object using the service.

● The same instance can be shared by several unrelated consumers.

● Services provide contracts, so implementation can be changed in the future.

What is the most appropriate lifetime for a database


connection/ORM context in an ASP.NET MVC application?
● Hide answer
● The lifetime should be the same as the request, because usually requests don’t
live very long. Where it’s possible to wrap the whole request in one transaction,
this can help comply with ACID principles.

[ASP.NET MVC 5] You have an ASP.NET MVC application


where you need to use ASP.NET session state and support
running across several servers. What additional
configuration can you perform without writing custom code?

Hide answer
In the Web.config file (in the root folder of your application)
set sessionState to StateServer for shared in-memory storage or SQLServer for
shared durable storage.

[ASP.NET Core MVC] You have an ASP.NET Core MVC


application where you need to use some cache solution and
support running across several servers. What are your
steps?

Hide answer
There are several answers, because ASP.NET Core is a new platform and supports
several approaches. The candidate has to stress that, in the project, we need to use
some kind of distributed cache—for example, Redis. Also, Microsoft provides several
packages to help with this. In the case of
Redis, Microsoft.Extensions.Caching.Redis provides the middleware and
implements IDistributedCache to provide a standardized way to work with it.
What is the difference between asynchronous and
synchronous actions? When would you use asynchronous
actions?
Hide answer
Asynchronous actions won’t block the executing thread if it waits for an I/O operation.
Using asynchronous actions can increase the throughput of a system if you use such a
pattern for I/O operations, but it won’t help with CPU-bound operations.

[ASP.NET MVC 5] You have a page with Razor C# syntax.


What is the difference between these two
methods, RenderAction and RenderPartial? What will they do?
@{
Html.RenderAction("Add");
Html.RenderPartial("Add");
}

RenderAction will call an action method of the current controller and render a result inline. In
contrast, RenderPartial will render the specified view inline without calling any action method.

Breifly explain us what is ASP.Net MVC?


ASP.Net MVC is a pattern which is used to split the application's implementation logic into
three components i.e. models, views, and controllers.

Tell us something about Model, view and Controllers in Asp.Net MVC?


Model : It is basically a business entity which is used to represent the application data.
Controller : The Request which is sent by the user always scatters through controller and it's
responsibility is to redirect to the specific view using View () method. View : it's the
presentation layer of ASP.Net MVC.
Do you know about the new features in ASP.Net MVC 4 (ASP.Net MVC4)?
Following are features added newly : Mobile templates Added ASP.NET Web API template for
creating REST based services. Asynchronous controller task support. Bundling of the java
scripts. Segregating the configs for ASP.Net MVC routing, Web API, Bundle etc.

How does the 'page lifecycle' of ASP.Net MVC works?


Below are the processed followed in the sequence -

● App initializWhat is Separation of Concerns in ASP.NET ASP.Net MVCation


● Routing
● Instantiate and execute controller
● Locate and invoke controller action
● Instantiate and render view.

Explain the advantages of ASP.Net MVC over ASP.NET?

● Provides a clean separation of concerns among UI (Presentation layer), model (Transfer


objects/Domain Objects/Entities) and Business Logic (Controller).
● Easy to UNIT Test.
● Improved reusability of model and views. We can have multiple views which can point to
the same model and vice versa.
● Improved structuring of the code.

What is Separation of Concerns in ASP.NET ASP.Net MVC?


It is the process of breaking the program into various distinct features which overlaps in
functionality as little as possible. ASP.Net MVC pattern concerns on separating the content
from presentation and data-processing from content.

What is Razor View Engine?

Razor is the first major update to render HTML in ASP.Net MVC 3. Razor was designed
specifically for view engine syntax. Main focus of this would be to simplify and code-focused
templating for HTML generation. Below is the sample of using Razor:
@model ASP.Net MVCMusicStore.Models.Customer
@{ViewBag.Title = "Get Customers";}
< div class="cust"> <h3><em>@Model.CustomerName</<em> </<h3><div>

What is the meaning of Unobtrusive JavaScript? Explain us by any practical


example.
This is a general term that conveys a general philosophy, similar to the term REST
(Representational State Transfer). Unobtrusive JavaScript doesn't inter mix JavaScript code in
your page markup. Eg : Instead of using events like onclick and onsubmit, the unobtrusive
JavaScript attaches to elements by their ID or class based on the HTML5 data- attributes.

What is the use of View Model in ASP.Net MVC?


View Model is a plain class with properties, which is used to bind it to strongly typed view.
View Model can have the validation rules defined for its properties using data annotations.

What you mean by Routing in ASP.Net MVC?


Routing is a pattern matching mechanism of incoming requests to the URL patterns which are
registered in route table. Class : "UrlRoutingModule" is used for the same process.

What are Actions in ASP.Net MVC?


Actions are the methods in Controller class which is responsible for returning the view or json
data. Action will mainly have return type : "ActionResult" and it will be invoked from method :
"InvokeAction()" called by controller.

What is Attribute Routing in ASP.Net MVC?


ASP.NET Web API supports this type routing. This is introduced in ASP.Net MVC5. In this
type of routing, attributes are being used to define the routes. This type of routing gives more
control over classic URI Routing. Attribute Routing can be defined at controller level or at
Action level like :
[Route("{action = TestCategoryList}")] - Controller Level
[Route("customers/{TestCategoryId:int:min(10)}")] - Action Level

How to enable Attribute Routing?


Just add @Model.CustomerName the method : "MapASP.Net MVCAttributeRoutes()" to enable
attribute routing as shown below:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//enabling attribute routing
routes.MapASP.Net MVCAttributeRoutes();
//convention-based routing
routes.MapRoute
(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Customer", action =
"GetCustomerList", id = UrlParameter.Optional }
);
}

Explain JSON Binding?


JavaScript Object Notation (JSON) binding support started from ASP.Net MVC3 onwards via
the new JsonValueProviderFactory, which allows the action methods to accept and model-bind
data in JSON format. This is useful in Ajax scenarios like client templates and data binding that
need to post data back to the server.

Explain Dependency Resolution?


Dependency Resolver again has been introduced in ASP.Net MVC3 and it is greatly simplified
the use of dependency injection in your applications. This turn to be easier and useful for
decoupling the application components and making them easier to test and more configurable.

Explain Bundle.Config in ASP.Net MVC4?


"BundleConfig.cs" in ASP.Net MVC4 is used to register the bundles by the bundling and
minification system. Many bundles are added by default including jQuery libraries like -
jquery.validate, Modernizr, and default CSS references.

How route table has been created in ASP.NET ASP.Net MVC?


Method : "RegisterRoutes()" is used for registering the routes which will be added in
"Application_Start()" method of global.asax file, which is fired when the application is loaded
or started.

Which are the important namespaces used in ASP.Net MVC?


Below are the important namespaces used in ASP.Net MVC -

● System.Web.ASP.Net MVC
● System.Web.ASP.Net MVC.Ajax
● System.Web.ASP.Net MVC.Html
● System.Web.ASP.Net MVC.Async

What is ViewData?
Viewdata contains the key, value pairs as dictionary and this is derived from class :
"ViewDataDictionary". In action method we are setting the value for viewdata and in view the
value will be fetched by typecasting.

What is the difference between ViewBag and ViewData in ASP.Net MVC?


ViewBag is a wrapper around ViewData, which allows to create dynamic properties. Advantage
of viewbag over viewdata will be : In ViewBag no need to typecast the objects as in ViewData.
ViewBag will take advantage of dynamic keyword which is introduced in version 4.0. But
before using ViewBag we have to keep in mind that ViewBag is slower than ViewData.

Explain TempData in ASP.Net MVC?


TempData is again a key, value pair as ViewData. This is derived from "TempDataDictionary"
class. TempData is used when the data is to be used in two consecutive requests, this could be
between the actions or between the controllers. This requires typecasting in view.

What are HTML Helpers in ASP.Net MVC?


HTML Helpers are like controls in traditional web forms. But HTML helpers are more
lightweight compared to web controls as it does not hold viewstate and events. HTML Helpers
returns the HTML string which can be directly rendered to HTML page. Custom HTML
Helpers also can be created by overriding "HtmlHelper" class.

What are AJAX Helpers in ASP.Net MVC?


AJAX Helpers are used to create AJAX enabled elements like as Ajax enabled forms and links
which performs the request asynchronously and these are extension methods of AJAXHelper
class which exists in namespace - System.Web.ASP.Net MVC.

What are the options can be configured in AJAX helpers?


Below are the options in AJAX helpers :

● Url : This is the request URL.


● Confirm : This is used to specify the message which is to be displayed in confirm box.
● OnBegin : Javascript method name to be given here and this will be called before the
AJAX request.
● OnComplete : Javascript method name to be given here and this will be called at the end
of AJAX request.
● OnSuccess - Javascript method name to be given here and this will be called when AJAX
request is successful.
● OnFailure - Javascript method name to be given here and this will be called when AJAX
request is failed.
● UpdateTargetId : Target element which is populated from the action returning HTML.

What is Layout in ASP.Net MVC?


Layout pages are similar to master pages in traditional web forms. This is used to set the
common look across multiple pages. In each child page we can find : /p>
@{
Layout = "~/Views/Shared/TestLayout1.cshtml";
}
This indicates child page uses TestLayout page as it's master page.

Explain Sections is ASP.Net MVC?


Section are the part of HTML which is to be rendered in layout page. In Layout page we will
use the below syntax for rendering the HTML :
@RenderSection("TestSection")
And in child pages we are defining these sections as shown below :
@section TestSection{
<h1>Test Content<h1>
}
If any child page does not have this section defined then error will be thrown so to avoid that we
can render the HTML like this :
@RenderSection("TestSection", required: false)

Can you explain RenderBody and RenderPage in ASP.Net MVC?


RenderBody is like ContentPlaceHolder in web forms. This will exist in layout page and it will
render the child pages/views. Layout page will have only one RenderBody() method.
RenderPage also exists in Layout page and multiple RenderPage() can be there in Layout page.

What is ViewStart Page in ASP.Net MVC?


This page is used to make sure common layout page will be used for multiple views. Code
written in this file will be executed first when application is being loaded.
Explain the methods used to render the views in ASP.Net MVC?
Below are the methods used to render the views from action -

● View() : To return the view from action.


● PartialView() : To return the partial view from action.
● RedirectToAction() : To Redirect to different action which can be in same controller or in
different controller.
● Redirect() : Similar to "Response.Redirect()" in webforms, used to redirect to specified
URL.
● RedirectToRoute() : Redirect to action from the specified URL but URL in the route table
has been matched.

What are the sub types of ActionResult?


ActionResult is used to represent the action method result. Below are the subtypes of
ActionResult :

● ViewResult
● PartialViewResult
● RedirectToRouteResult
● RedirectResult
● JavascriptResult
● JSONResult
● FileResult
● HTTPStatusCodeResult

What are Non Action methods in ASP.Net MVC?


In ASP.Net MVC all public methods have been treated as Actions. So if you are creating a
method and if you do not want to use it as an action method then the method has to be decorated
with "NonAction" attribute as shown below :
[NonAction]
public void TestMethod()
{
// Method logic
}

How to change the action name in ASP.Net MVC?


"ActionName" attribute can be used for changing the action name. Below is the sample code
snippet to demonstrate more :
[ActionName("TestActionNew")]
public ActionResult TestAction()
{
return View();
}
So in the above code snippet "TestAction" is the original action name and in "ActionName"
attribute, name - "TestActionNew" is given. So the caller of this action method will use the name
"TestActionNew" to call this action.

What are Code Blocks in Views?


Unlike code expressions that are evaluated and sent to the response, it is the blocks of code that
are executed. This is useful for declaring variables which we may be required to be used later.
@{
int x = 123;
string y = "aa";
}

What is the "HelperPage.IsAjax" Property?


The HelperPage.IsAjax property gets a value that indicates whether Ajax is being used during
the request of the Web page.
How we can call a JavaScript function on the change of a Dropdown List in
ASP.Net MVC?
Create a JavaScript method:
function DrpIndexChanged() { }
Invoke the method:
< %:Html.DropDownListFor(x => x.SelectedProduct, new
SelectList(Model.Customers, "Value", "Text"), "Please Select a
Customer", new { id = "ddlCustomers", onchange=" DrpIndexChanged ()"
})%>

What are Validation Annotations?


Data annotations are attributes which can be found in the
"System.ComponentModel.DataAnnotations" namespace. These attributes will be used for
server-side validation and client-side validation is also supported. Four attributes - Required,
String Length, Regular Expression and Range are used to cover the common validation
scenarios.

Why to use Html.Partial in ASP.Net MVC?


This method is used to render the specified partial view as an HTML string. This method does
not depend on any action methods. We can use this like below :
@Html.Partial("TestPartialView")
What is Html.RenderPartial?
Result of the method : "RenderPartial" is directly written to the HTML response. This method
does not return anything (void). This method also does not depend on action methods.
RenderPartial() method calls "Write()" internally and we have to make sure that "RenderPartial"
method is enclosed in the bracket. Below is the sample code snippet :
@{Html.RenderPartial("TestPartialView"); }

What is RouteConfig.cs in ASP.Net MVC 4?


"RouteConfig.cs" holds the routing configuration for ASP.Net MVC. RouteConfig will be
initialized on Application_Start event registered in Global.asax.

What are Scaffold templates in ASP.Net MVC?


Scaffolding in ASP.NET ASP.Net MVC is used to generate the Controllers,Model and Views
for create, read, update, and delete (CRUD) functionality in an application. The scaffolding will
be knowing the naming conventions used for models and controllers and views.
Explain the types of Scaffoldings.
Below are the types of scaffoldings :

● Empty
● Create
● Delete
● Details
● Edit
● List
Can a view be shared across multiple controllers? If Yes, How we can do that?
Yes we can share a view across multiple controllers. We can put the view in the "Shared" folder.
When we create a new ASP.Net MVC Project we can see the Layout page will be added in the
shared folder, which is because it is used by multiple child pages.

What are the components required to create a route in ASP.Net MVC?

● Name - This is the name of the route.


● URL Pattern : Placeholders will be given to match the request URL pattern.
● Defaults :When loading the application which controller, action to be loaded along with
the parameter.

Why to use "{resource}.axd/{*pathInfo}" in routing in ASP.Net MVC?


Using this default route - {resource}.axd/{*pathInfo}, we can prevent the requests for the web
resources files like - WebResource.axd or ScriptResource.axd from passing to a controller.
Can we add constraints to the route? If yes, explain how we can do it?
Yes we can add constraints to route in following ways :

● Using Regular Expressions


● Using object which implements interface - IRouteConstraint.
What are the possible Razor view extensions?
Below are the two types of extensions razor view can have :

● .cshtml : In C# programming language this extension will be used.


● .vbhtml - In VB programming language this extension will be used.

What is PartialView in ASP.Net MVC?


PartialView is similar to UserControls in traditional web forms. For re-usability purpose partial
views are used. Since it's been shared with multiple views these are kept in shared folder. Partial
Views can be rendered in following ways :

● Html.Partial()
● Html.RenderPartial()

How we can add the CSS in ASP.Net MVC?


Below is the sample code snippet to add css to razor views : < link rel="StyleSheet"
href="/@Href(~Content/Site.css")" type="text/css"/>

Can I add ASP.Net MVC Testcases in Visual Studio Express?


No. We cannot add the test cases in Visual Studio Express edition it can be added only in
Professional and Ultimate versions of Visual Studio.
What is the use .Glimpse in ASP.Net MVC?
Glimpse is an open source tool for debugging the routes in ASP.Net MVC. It is the client side
debugger. Glimpse has to be turned on by visiting to local url link -
http://localhost:portname//glimpse.axd This is a popular and useful tool for debugging which
tracks the speed details, url details etc.

What is the need of Action Filters in ASP.Net MVC?


Action Filters allow us to execute the code before or after action has been executed. This can be
done by decorating the action methods of controls with ASP.Net MVC attributes.

Mention some action filters which are used regularly in ASP.Net MVC?
Below are some action filters used :

● Authentication
● Authorization
● HandleError
● OutputCache

How can we determine action invoked from HTTP GET or HTTP POST?
This can be done in following way : Use class : "HttpRequestBase" and use the method :
"HttpMethod" to determine the action request type.

In Server how to check whether model has error or not in ASP.Net MVC?
Whenever validation fails it will be tracked in ModelState. By using property : IsValid it can be
determined. In Server code, check like this :
if(ModelState.IsValid){
// No Validation Errors
}

How to make sure Client Validation is enabled in ASP.Net MVC?


In Web.Config there are tags called : "ClientValidationEnabled" and
"UnobtrusiveJavaScriptEnabled". We can set the client side validation just by setting these two
tags "true", then this setting will be applied at the application level.
< add key="ClientValidationEnabled" value="true" />
< add key="UnobtrusiveJavaScriptEnabled" value="true" />

What are Model Binders in ASP.Net MVC?


For Model Binding we will use class called : "ModelBinders", which gives access to all the
model binders in an application. We can create a custom model binders by inheriting
"IModelBinder".

How we can handle the exception at controller level in ASP.Net MVC?


Exception Handling is made simple in ASP.Net MVC and it can be done by just overriding
"OnException" and set the result property of the filtercontext object (as shown below) to the
view detail, which is to be returned in case of exception.
protected overrides void OnException(ExceptionContext filterContext)
{
}

Does Tempdata hold the data for other request in ASP.Net MVC?
If Tempdata is assigned in the current request then it will be available for the current request and
the subsequent request and it depends whether data in TempData read or not. If data in
Tempdata is read then it would not be available for the subsequent requests.

Explain Keep method in Tempdata in ASP.Net MVC?


As explained above in case data in Tempdata has been read in current request only then "Keep"
method has been used to make it available for the subsequent request.
@TempData["TestData"];
TempData.Keep("TestData");

Explain Peek method in Tempdata in ASP.Net MVC?


Similar to Keep method we have one more method called "Peek" which is used for the same
purpose. This method used to read data in Tempdata and it maintains the data for subsequent
request.
string A4str = TempData.Peek("TT").ToString();
What is Area in ASP.Net MVC?
Area is used to store the details of the modules of our project. This is really helpful for big
applications, where controllers, views and models are all in main controller, view and model
folders and it is very difficult to manage.

How we can register the Area in ASP.Net MVC?


When we have created an area make sure this will be registered in "Application_Start" event in
Global.asax. Below is the code snippet where area registration is done :
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
}

What are child actions in ASP.Net MVC?


To create reusable widgets child actions are used and this will be embedded into the parent
views. In ASP.Net MVC Partial views are used to have reusability in the application. Child
action mainly returns the partial views.

How we can invoke child actions in ASP.Net MVC?


"ChildActionOnly" attribute is decorated over action methods to indicate that action method is a
child action. Below is the code snippet used to denote the child action :
[ChildActionOnly]
public ActionResult MenuBar()
{
//Logic here
return PartialView();
}

What is Dependency Injection in ASP.Net MVC?


it's a design pattern and is used for developing loosely couple code. This is greatly used in the
software projects. This will reduce the coding in case of changes on project design so this is
vastly used.

Explain the advantages of Dependency Injection (DI) in ASP.Net MVC?


Below are the advantages of DI :

● Reduces class coupling


● Increases code reusing
● Improves code maintainability
● Improves application testing

Explain Test Driven Development (TDD) ?


TDD is a methodology which says, write your tests first before you write your code. In TDD,
tests drive your application design and development cycles. You do not do the check-in of your
code into source control until all of your unit tests pass.

Explain the tools used for unit testing in ASP.Net MVC?


Below are the tools used for unit testing :

● NUnit
● xUnit.NET
● Ninject 2
● Moq
What is Representational State Transfer (REST) mean?
REST is an architectural style which uses HTTP protocol methods like GET, POST, PUT, and
DELETE to access the data. ASP.Net MVC works in this style. In ASP.Net MVC 4 there is a
support for Web API which uses to build the service using HTTP verbs.

How to use Jquery Plugins in ASP.Net MVC validation?


We can use dataannotations for validation in ASP.Net MVC. If we want to use validation during
runtime using Jquery then we can use Jquery plugins for validation. Eg: If validation is to be
done on customer name textbox then we can do as :
$('#CustomerName').rules("add", {
required: true,
minlength: 2,
messages: {
required: "Please enter name",
minlength: "Minimum length is 2"
}
});

How we can multiple submit buttons in ASP.Net MVC?


Below is the scenario and the solution to solve multiple submit buttons issue. Scenario :
@using (Html.BeginForm("MyTestAction","MyTestController")
{
<input type="submit" value="MySave" />
<input type="submit" value="MyEdit" />
}
Solution :
Public ActionResult MyTestAction(string submit) //submit will have
value either "MySave" or "MyEdit"
{
// Write code here
}

What are the differences between Partial View and Display Template and Edit
Templates in ASP.Net MVC?

● Display Templates : These are model centric. Meaning it depends on the properties of the
view model used. It uses convention that will only display like divs or labels.
● Edit Templates : These are also model centric but will have editable controls like
Textboxes.
● Partial View : These are view centric. These will differ from templates by the way they
render the properties (Id's) Eg : CategoryViewModel has Product class property then it
will be rendered as Model.Product.ProductName but in case of templates if we
CategoryViewModel has List then @Html.DisplayFor(m => m.Products) works and it
renders the template for each item of this list.

Can I set the unlimited length for "maxJsonLength" property in config?


No. We can't set unlimited length for property maxJsonLength. Default value is - 102400 and
maximum value what we can set would be : 2147483644.

Can I use Razor code in Javascript in ASP.Net MVC?


Yes. We can use the razor code in javascript in cshtml by using <text> element.
< script type="text/javascript">
@foreach (var item in Model) {
< text >
//javascript goes here which uses the server values
< text >
}
< script>

How can I return string result from Action in ASP.Net MVC?


Below is the code snippet to return string from action method :
public ActionResult TestAction() {
return Content("Hello Test !!");
}

How to return the JSON from action method in ASP.Net MVC?


Below is the code snippet to return string from action method :
public ActionResult TestAction() {
return JSON(new { prop1 = "Test1", prop2 = "Test2" });
}

1) Explain what is Model-View-Controller?

MVC is a software architecture pattern for developing web application. It is


handled by three objects Model-View-Controller.

2) Mention what does Model-View-Controller represent in an MVC


application?

In an MVC model,

● Model- It represents the application data domain. In other words


applications business logic is contained within the model and is
responsible for maintaining data
● View- It represents the user interface, with which the end users
communicates. In short all the user interface logic is contained within
the VIEW
● Controller- It is the controller that answers to user actions. Based on
the user actions, the respective controller responds within the model
and choose a view to render that display the user interface. The user
input logic is contained with-in the controller

3) Explain in which assembly is the MVC framework is defined?

The MVC framework is defined in System.Web.Mvc.

4) List out few different return types of a controller action method?

● View Result
● Javascript Result
● Redirect Result
● Json Result
● Content Result

5) Mention what is the difference between adding routes, to a webform


application and an MVC application?

To add routes to a webform application, we can use MapPageRoute() method


of the RouteCollection class, where adding routes to an MVC application, you
can use MapRoute() method.

6) Mention what are the two ways to add constraints to a route?


The two methods to add constraints to a route is

● Use regular expressions


● Use an object that implements IRouteConstraint Interface

7) Mention what is the advantages of MVC?

● MVC segregates your project into a different segment, and it becomes


easy for developers to work on
● It is easy to edit or change some part of your project that makes project
less development and maintenance cost
● MVC makes your project more systematic

8) Mention what "beforFilter()","beforeRender" and "afterFilter"


functions do in Controller?

● beforeFilter(): This function is run before every action in the controller.


It's the right place to check for an active session or inspect user
permissions.
● beforeRender(): This function is called after controller action logic, but
before the view is rendered. This function is not often used, but may be
required If you are calling render() manually before the end of a given
action
● afterFilter(): This function is called after every controller action, and
after rendering is done. It is the last controller method to run

9) Explain the role of components Presentation, Abstraction and Control


in MVC?

● Presentation: It is the visual representation of a specific abstraction


within the application
● Abstraction: It is the business domain functionality within the
application
● Control: It is a component that keeps consistency between the
abstraction within the system and their presentation to the user in
addition to communicating with other controls within the system

10) Mention the advantages and disadvantages of MVC model?


Advantages Disadvantages

● It represents clear separation ● The model pattern is little complex


between business logic and ● Inefficiency of data access in view
presentation logic ● With modern user interface, it is
● Each MVC object has different difficult to use MVC
responsibilities ● You need multiple programmers for
● The development progresses in parallel development
parallel ● Multiple technologies knowledge is
● Easy to manage and maintain required
● All classes and object are
independent of each other

11) Explain the role of "ActionFilters" in MVC?

In MVC " ActionFilters" help you to execute logic while MVC action is
executed or its executing.

12) Explain what are the steps for the execution of an MVC project?

The steps for the execution of an MVC project includes

● Receive first request for the application


● Performs routing
● Creates MVC request handler
● Create Controller
● Execute Controller
● Invoke action
● Execute Result

13) Explain what is routing? What are the three segments for routing is
important?

Routing helps you to decide a URL structure and map the URL with the
Controller.

The three segments that are important for routing is

● ControllerName
● ActionMethodName
● Parameter

14) Explain how routing is done in MVC pattern?

There is a group of routes called the RouteCollection, which consists of


registered routes in the application. The RegisterRoutes method records the
routes in this collection. A route defines a URL pattern and a handler to use if
the request matches the pattern. The first parameter to the MapRoute method
is the name of the route. The second parameter will be the pattern to which
the URL matches. The third parameter might be the default values for the
placeholders if they are not determined.

15) Explain using hyperlink how you can navigate from one view to other
view?

By using "ActionLink" method as shown in the below code. The below code
will make a simple URL which help to navigate to the "Home" controller and
invoke the "GotoHome" action.

Collapse / Copy Code

<%= Html.ActionLink("Home", "Gotohome") %>

16) Mention how can maintain session in MVC?

Session can be maintained in MVC by three ways tempdata, viewdata, and


viewbag.

17) Mention what is the difference between Temp data, View, and View
Bag?

● Temp data: It helps to maintain data when you shift from one controller
to other controller.
● View data: It helps to maintain data when you move from controller to
view
● View Bag: It's a dynamic wrapper around view data

18) What is partial view in MVC?


Partial view in MVC renders a portion of view content. It is helpful in reducing
code duplication. In simple terms, partial view allows to render a view within
the parent view.

19) Explain how you can implement Ajax in MVC?

In MVC, Ajax can be implemented in two ways

● Ajax libraries
● Jquery

20) Mention what is the difference between "ActionResult" and


"ViewResult" ?

"ActionResult" is an abstract class while "ViewResult" is derived from


"AbstractResult" class. "ActionResult" has a number of derived classes like
"JsonResult", "FileStreamResult" and "ViewResult" .

"ActionResult" is best if you are deriving different types of view dynamically.

21) Explain how you can send the result back in JSON format in MVC?

In order to send the result back in JSON format in MVC, you can use
"JSONRESULT" class.

22) Explain what is the difference between View and Partial View?

View Partial View

● It contains the layout page ● It does not contain the layout page
● Before any view is rendered, viewstart ● Partial view does not verify for a
page is rendered viewstart.cshtml. We cannot put
● View might have markup tags like common code for a partial view
body, html, head, title, meta etc.
● View is not lightweight as compare to within the viewStart.cshtml.page
Partial View
● Partial view is designed specially to
render within the view and just
because of that it does not consist
any mark up

● We can pass a regular view to the


RenderPartial method

23) List out the types of result in MVC?

In MVC, there are twelve types of results in MVC where "ActionResult" class
is the main class while the 11 are their sub-types

● ViewResult
● PartialViewResult
● EmptyResult
● RedirectResult
● RedirectToRouteResult
● JsonResult
● JavaScriptResult
● ContentResult
● FileContentResult
● FileStreamResult
● FilePathResult

24) Mention what is the importance of NonActionAttribute?

All public methods of a controller class are treated as the action method if you
want to prevent this default method then you have to assign the public method
with NonActionAttribute.

25) Mention what is the use of the default route


{resource}.axd/{*pathinfo} ?

This default route prevents request for a web resource file such as
Webresource.axd or ScriptResource.axd from being passed to the controller.

26) Mention the order of the filters that get executed, if the multiple
filters are implemented?

The filter order would be like


● Authorization filters
● Action filters
● Response filters
● Exception filters

27) Mention what filters are executed in the end?

In the end "Exception Filters" are executed.

28) Mention what are the file extensions for razor views?

For razor views the file extensions are

● .cshtml: If C# is the programming language


● .vbhtml: If VB is the programming language

29) Mention what are the two ways for adding constraints to a route?

Two methods for adding constraints to route is

● Using regular expressions


● Using an object that implements IRouteConstraint interface

30) Mention two instances where routing is not implemented or


required?

Two instance where routing is not required are

● When a physical file is found that matches the URL pattern


● When routing is disabled for a URL pattern

31) Mention what are main benefits of using MVC?

There are two key benefits of using MVC

● As the code is moved behind a separate class file, you can use the
code to a great extent
● As behind code is simply moved to.NET class, it is possible to automate
UI testing. This gives an opportunity to automate manual testing and
write unit tests.
1. Mention what does Model-View-Controller represent
in an MVC application?
Components Description

It represents the application data domain.


In other words, applications business logic
Model
is contained within the model and is
responsible for maintaining data.

It represents the user interface, with which


the end-users communicates. In short, all
View
the user interface logic is contained within
the VIEW.

It is the controller that answers to user


actions. Based on the user actions, the
respective controller responds within the
Controller
model and choose a view to render that
display the user interface. The user input
logic is contained with-in the controller.

2. Explain what is MVC?

MVC is an abbreviation for Model, View, and Controller. The MVC architectural
pattern separates an application into three components – Model, View, and Controller.
In this pattern, the model represents the shape of the data and business logic. It
maintains and preserves the data of the application. Model objects retrieve and store
model state in a database. The view is basically and technically a user interface. The
view segment displays the data-using model to the user and also enables them to
modify the data. The controller is the part, which handles the user request.

3. List out a few different return types of a controller


action method?
● View Result
● Javascript Result
● Redirect Result
● JSON Result
● Content Result

4. What are the advantages of MVC?


Benefits or the advantages of MVC are as follows:

● Multiple view support: Because of the separation of the model from the view,
the user interface can display multiple views of the same data and at the same
time.
● Change Accommodation: User interfaces tend to change more frequently than
business rules.
● SoC – Separation of Concerns: Separation of Concerns is one of the core
advantages of ASP.NET MVC. The MVC framework provides a clean separation
of the UI, Business Logic, Model or Data.
● More Control: The ASP.NET MVC framework provides more control
over HTML, JavaScript, and CSS than the traditional WebForms.
● Testability: This framework provides better testability of the Web Application and
good support for the test-driven development too.
● Lightweight: MVC framework doesn’t use View State and that reduces the
bandwidth of the requests to an extent.

5. Explain the role of components Presentation,


Abstraction, and Control in MVC?
● Presentation: It is the visual representation of a specific abstraction within the
application.
● Abstraction: It is the business domain functionality within the application.
● Control: It is a component that keeps consistency between the abstraction within
the system and their presentation to the user. It is also used to communicate with
other controls within the system.
6. How to maintain session in MVC?
The session can be maintained in MVC by three ways temp data, viewdata, and view
bag.

7. What is MVC Application life cycle?


Any web application has two main execution steps, first understanding the request and
depending on the type of the request, sending out an appropriate response. MVC
application life cycle has two main phases, first creating the request object and second
sending the response to the browser.

Creating the request object includes four basic steps:

Step 1: Fill route

Step 2: Fetch route

Step 3: Request context created

Step 4: Controller instance created

8. What does the MVC Pattern define with 3 logical


layers?
The MVC model defines web applications with 3 logic layers:

● The business layer (Model logic)


● The display layer (View logic)
● The input control (Controller logic)

The Model is the part of the application, which only handles the logic for the application
data. Regularly, the model objects retrieve data (as well as store data) from a database.
The View is the part of the application, which takes care of the display of the data. Most
often, the views are created from the model data, although there are other, more
complicated methods of creating views. The Controller, as the name implies, is the part
of the application that handles user interaction.

9. What is Spring MVC?


It is a Java framework which is used to build web applications. It follows
the Model-View-Controller design pattern. Not just that, it also implements all the
basic features of a core Spring Framework like Inversion of Control, Dependency
Injection. Spring MVC provides a dignified solution to use MVC in Spring Framework by
the help of DispatcherServlet. In this case, DispatcherServlet is a class that receives
the incoming request and maps it to the right resource such as Controllers, Models,
and Views.

10. What is ASP.NET MVC?


ASP.NET MVC is a web application Framework. It is lightweight and highly testable
Framework. MVC separates an application into three components — Model, View, and
Controller.

11. What is MVC Routing?


The URLs in ASP.NET MVC are mapped to action methods and controller instead of
physical files of the system. To accurately map action methods and controller to URLs,
the routing engine forms appropriate routes. Using this, the controllers can handle
specific requests.

12. What are the Filters?


Sometimes we want to execute some logic either before the execution of the action
method or after the execution. We can use Action Filter for such kind of scenario. Filters
define the logic which is executed before or after the execution of the action method.
Action Filters are attributes which we can apply to the action methods. Following are the
MVC action filter types:

1. Authorization filter (implements IAuthorizationFilter)


2. Action filter (implements IActionFilter)
3. Result filter (implements IResultFilter)
4. Exception filter (implementsIExceptionFilter attribute)

13. What is Partial View in MVC?


A partial view is a chunk of HTML that can be safely inserted into an existing DOM.
Most commonly, partial views are used to componentize Razor views and make them
easier to build and update. It can also be returned directly from controller methods. In
this case, the browser still receives text/HTML content but not
necessarily HTML content that makes up an entire page. As a result, if a URL that
returns a partial view is directly invoked from the address bar of a browser, an
incomplete page may be displayed. This may be something like a page that misses title,
script and style sheets.

14. Can you explain the page life cycle of MVC?


Below mentioned steps define the page life cycle.

● App initialization
● Routing
● Instantiate and execute controller
● Locate and invoke controller action
● Instantiate and render view.

15. What is the use of ViewModel in MVC?


ViewModel is a plain class with properties, which is used to bind it to a
strongly-typed view. ViewModel can have the validation rules defined for its properties
using data annotation.

Intermediate level Questions


16. What is Database first approach in MVC using
Entity Framework?
Database First Approach is an alternative or substitutes to the Code First and Model
First approaches to the Entity Data Model. The Entity Data Model creates model codes
(classes, properties, DbContext, etc.) from the database in the project and
that class behaves as the link between database and controller.

There are the following approaches, which are used to connect the database with the
application.

● Database First
● Model First
● Code First

17. What do you mean by MVC Scaffolding?


Scaffolding is a code generation framework for ASP.NET Web applications. Visual
Studio includes pre-installed code generators for MVC and Web API projects. You add
scaffolding to your project when you want to quickly add the code that interacts with
data models. Using scaffolding can reduce the amount of time to develop standard data
operations in your project.
It consists of page templates, entity page templates, field page templates, and filter
templates. These templates are called Scaffold templates and they allow you to quickly
build a functional data-driven Website.

18. Explain the concept of Razor in ASP.NET MVC?


ASP.NET MVC has always supported the concept of “view engines” – which are the
pluggable modules that implement different template syntax options. The “default” view
engine for ASP.NET MVC uses the same .aspx/.ascx/. master file templates as
ASP.NET WebForms. Other popular ASP.NET MVC view engines are Spart & Nhaml.
Razor is the new view-engine introduced by MVC 3.

19. Explain the concept of Default Route in MVC


Default Route: The default ASP.NET MVC project templates add a generic route that
uses the following URL convention to break the URL for a given request into three
named segments.

URL: "{controller}/{action}/{id}"

This route pattern is registered via a call to the MapRoute() extension method
of RouteCollection.

20. What is GET and POST Action types?


GET Action Type: GET is used to request data from a specified resource. With all the
GET requests, we pass the URL, which is compulsory; however, it can take up the
following overloads.

POST Action Type: Tthe POST is used to submit data to be processed to a specified
resource. With all the POST requests, we pass the URL, which is essential and the
data. However, it can take up the following overloads.

21. How does View Data differ from View Bag in MVC?
View Data View Bag

ViewData is used to pass data from a ViewBag is also used to pass data from the
controller to view controller to the respective view.
It is also available for the current request
It is available for the current request only.
only.

Requires typecasting for complex data type Doesn’t require typecasting for the complex
and checks for null values to avoid error data type.

If redirection occurs, then its value


becomes null.
If redirection occurs, then its value
becomes null.

22. Mention the Benefits of Area in MVC


Benefits of Area in MVC are as follows:

● It allows us to organize models, views, and controllers into separate functional


sections of the application, such as administration, billing, customer support and
much more.
● It is easy to integrate with other Areas created by another.
● Also, easy for unit testing.

23. Which filters are executed in the end?


In the end “Exception Filters” are executed.

24. Mention what are the two ways for adding


constraints to a route?
Two methods for adding constraints to the route is

● Using regular expressions


● Using an object that implements IRouteConstraint interface

25. How can we implement validation in MVC?


We can easily implement validation in MVC application by using the validators defined
in the System.ComponentModel.DataAnnotations namespace. There are different types
of validators as follows:

● Required
● DataType
● Range
● StringLength

26. Mention two instances where routing is not


implemented or required?
Two instances where routing is not required are:

● When a physical file is found that matches the URL pattern


● When routing is disabled for a URL pattern

27. Explain how you can implement Ajax in MVC?


In MVC, Ajax can be implemented in two ways. They are as follows:

● Ajax libraries
● Jquery

28. What is the use of Keep and Peek in “TempData”?


Once “TempData” is read in the current request, it’s not available in the subsequent
request. If we want “TempData” to be read and also available in the subsequent request
then after reading we need to call “Keep” method as shown in the code below.

1 @TempData["MyData"];
2 TempData.Keep("MyData");
The more shortcut way of achieving the same is by using “Peek”. This function helps to
read as well advices MVC to maintain “TempData” for the subsequent request.

1 string str = TempData.Peek("Td").ToString();

29. What is WebAPI?


HTTP is the most used protocol. Since many years, the browser was the most preferred
client by which we consumed data exposed over HTTP. But as years passed by, client
variety started spreading out. We had demanded to consume data on HTTP from clients
like mobile, JavaScript, Windows applications, etc.

For satisfying the broad range of clients, REST was the proposed approach. WebAPI is
the technology by which you can expose data over HTTP following REST principles.

30. How can we detect that an MVC controller is called


by POST or GET?
To detect if the call on the controller is a POST action or a GET action we can use
the Request.HttpMethod property as shown in the below code snippet.

1 public ActionResult SomeAction(){


2 if (Request.HttpMethod == "POST"){
3 return View("SomePage");
4 }
5 else{
6 return View("SomeOtherPage");
7 }
8 }
Now let’s move further and look at the Advanced MVC Interview questions.

Advanced Level MVC Interview Questions


31. What are the main Razor Syntax Rules
Following are the rules for main Razor Syntax:

● Razor code blocks are enclosed in @{ … }


● Inline expressions (variables and functions) start with @
● Code statements end with a semicolon
● Variables are declared with the var keyword
● Strings are enclosed with quotation marks
● C# code is case sensitive
● C# files have the extension .cshtml

32. How do you implement Forms authentication in


MVC?
Authentication is giving access to the user for a specific service by verifying his/her
identity using his/her credentials like username and password or email and password. It
assures that the correct user is authenticated or logged in for a specific service and the
right service has been provided to the specific user based on their role.

33. Can you explain RenderBody and RenderPage in


MVC?
RenderBody is like ContentPlaceHolder in web forms. This will exist in layout page and
it will render the child pages/views. Layout page will have only one RenderBody()
method. RenderPage also exists in Layout page and multiple RenderPage() can be
there in the Layout page.

34. What are Non Action methods in MVC?


In MVC all public methods have been treated as Actions. So if you are creating a
method and if you do not want to use it as an action method then the method has to be
decorated with “NonAction” attribute as shown below –

1 [NonAction]

2 public void TestMethod(){

3 // Method logic

4 }

35. How to perform Exception Handling in MVC?


In the controller, you can override the “OnException” event and set the “Result” to the
view name which you want to invoke when an error occurs. In the below code you can
see we have set the “Result” to a view named as “Error”.

We have also set the exception so that it can be displayed inside the view.

1
public class HomeController : Controller{
2
protected override void OnException(ExceptionContext filterContext){
3 Exception ex = filterContext.Exception;
4 filterContext.ExceptionHandled = true;
5 var model = new HandleErrorInfo(filterContext.Exception, "Controller","Action");
6 filterContext.Result = new ViewResult()
7 {
8 ViewName = "Error",
9 ViewData = new ViewDataDictionary(model)
10 };
}
11 }
12

36. Which is a better fit, Razor or ASPX?


As per Microsoft, Razor is more preferred because it’s lightweight and has simple
syntax’s.

37. What is Code Blocks in Views?


Unlike code expressions that are evaluated and sent to the response, it is the blocks of
code that are executed. This is useful for declaring variables which we may be required
to be used later.

1 @{

2 int x = 123;

3 string y = “aa”;

4 }

38. Why use Html.Partial in MVC?


This method is used to render the specified partial view as an HTML string. This method
does not depend on any action methods. We can use this like below –

1 @Html.Partial(“TestPartialView”)

39. What is a glimpse?


Glimpse is NuGet packages which help in finding performance, debugging and
diagnostic information. Glimpse can help you get information about timelines, model
binding, routes, environment, etc.

40. How can we navigate from one view to another


using a hyperlink?
By using the ActionLink method you can navigate. The below code will create a simple
URL which helps to navigate to the “Home” controller and invoke the Gotohome action.

1 <%= Html.ActionLink("Home","Gotohome") %>

1) What is ASP.NET MVC?


ASP.NET MVC is a web application Framework. It is light weight
and highly testable Framework. MVC separates application into
three components — Model, View and Controller.
2) Can you explain Model, Controller and View in MVC?

Model — It’s a business entity and it is used to represent the


application data.

Controller — Request sent by the user always scatters through


controller and it’s responsibility is to redirect to the specific view
using View() method.

View — It’s the presentation layer of MVC.

3)Explain the new features added in version 4 of MVC


(MVC4)?

Following are features added newly –

→Asynchronous controller task support.

→Bundling the java scripts.

→Segregating the configs for MVC routing, Web API, Bundle etc.

→Mobile templates

→Added ASP.NET Web API template for creating REST based


services.

→Asynchronous controller task support.

→Bundling the java scripts.


→Segregating the configs for MVC routing, Web API, Bundle etc.

4)Can you explain the page life cycle of MVC?

Below are the processed followed in the sequence -

→App initialization

→Routing

→Instantiate and execute controller

→Locate and invoke controller action

→Instantiate and render view.

5) What are the advantages of MVC over ASP.NET?

→Provides a clean separation of concerns among UI (Presentation


layer), model (Transfer objects/Domain Objects/Entities) and
Business Logic (Controller).

→Easy to UNIT Test.

→Improved reusability of model and views. We can have multiple


views which can point to the same model and vice versa.

→Improved structuring of the code.

6) What is Separation of Concerns in ASP.NET MVC?


It’s is the process of breaking the program into various distinct
features which overlaps in functionality as little as possible. MVC
pattern concerns on separating the content from presentation and
data-processing from content.

7) What is Razor View Engine?

Razor is the first major update to render HTML in MVC 3. Razor


was designed specifically for view engine syntax. Main focus of
this would be to simplify and code-focused templating for HTML
generation. Below is the sample of using Razor:

@model MvcMusicStore.Models.Customer

@{ViewBag.Title = “Get Customers”;}

<div class=”cust”> <h3><em>@Model.CustomerName</em>


</h3>

8) What is the meaning of Unobtrusive JavaScript?

This is a general term that conveys a general philosophy, similar


to the term REST (Representational State Transfer). Unobtrusive
JavaScript doesn’t intermix JavaScript code in your page markup.
Eg : Instead of using events like onclick and onsubmit, the
unobtrusive JavaScript attaches to elements by their ID or class
based on the HTML5 data- attributes.

9) What is the use of ViewModel in MVC?

ViewModel is a plain class with properties, which is used to bind it


to strongly typed view. ViewModel can have the validation rules
defined for its properties using data annotations.

10) What you mean by Routing in MVC?

Routing is a pattern matching mechanism of incoming requests to


the URL patterns which are registered in route table. Class —
“UrlRoutingModule” is used for the same process.

11) What are Actions in MVC?

Actions are the methods in Controller class which is responsible


for returning the view or json data. Action will mainly have return
type — “ActionResult” and it will be invoked from method —
“InvokeAction()” called by controller.

12) What is Attribute Routing in MVC?

ASP.NET Web API supports this type routing. This is introduced


in MVC5. In this type of routing, attributes are being used to
define the routes. This type of routing gives more control over
classic URI Routing. Attribute Routing can be defined at
controller level or at Action level like –

[Route(“{action = TestCategoryList}”)] — Controller Level


[Route(“customers/{TestCategoryId:int:min(10)}”)] — Action
Level

13) How to enable Attribute Routing?

Just add the method — “MapMvcAttributeRoutes()” to enable


attribute routing as shown below

public static void RegistearRoutes(RouteCollection routes)

routes.IgnoareRoute(“{resource}.axd/{*pathInfo}”);

//enabling attribute routing

routes.MapMvcAttributeRoutes();

//convention-based routing

routes.MapRoute

name: “Default”,

url: “{controller}/{action}/{id}”,

defaults: new { controller = “Customer”, action =


“GetCustomerList”, id = UrlParameter.Optional }
);

14) Explain JSON Binding?

JavaScript Object Notation (JSON) binding support started from


MVC3 onwards via the new JsonValueProviderFactory, which
allows the action methods to accept and model-bind data in JSON
format. This is useful in Ajax scenarios like client templates and
data binding that need to post data back to the server.

15) Explain Dependency Resolution?

Dependency Resolver again has been introduced in MVC3 and it


is greatly simplified the use of dependency injection in your
applications. This turn to be easier and useful for decoupling the
application components and making them easier to test and more
configurable.

16) Explain Bundle.Config in MVC4?

“BundleConfig.cs” in MVC4 is used to register the bundles by the


bundling and minification system. Many bundles are added by
default including jQuery libraries like — jquery.validate,
Modernizr, and default CSS references.

17) How route table has been created in ASP.NET MVC?

Method — “RegisterRoutes()” is used for registering the routes


which will be added in “Application_Start()” method of
global.asax file, which is fired when the application is loaded or
started.

18) Which are the important namespaces used in MVC?

Below are the important namespaces used in MVC -

System.Web.Mvc

System.Web.Mvc.Ajax

System.Web.Mvc.Html

System.Web.Mvc.Async

19) What is ViewData?

Viewdata contains the key, value pairs as dictionary and this is


derived from class — “ViewDataDictionary“. In action method we
are setting the value for viewdata and in view the value will be
fetched by typecasting.

20) What is the difference between ViewBag and


ViewData in MVC?

ViewBag is a wrapper around ViewData, which allows to create


dynamic properties. Advantage of viewbag over viewdata will be –

In ViewBag no need to typecast the objects as in ViewData.


ViewBag will take advantage of dynamic keyword which is
introduced in version 4.0. But before using ViewBag we have to
keep in mind that ViewBag is slower than ViewData.

21) Explain TempData in MVC?

TempData is again a key, value pair as ViewData. This is derived


from “TempDataDictionary” class. TempData is used when the
data is to be used in two consecutive requests, this could be
between the actions or between the controllers. This requires
typecasting in view.

22) What are HTML Helpers in MVC?

HTML Helpers are like controls in traditional web forms. But


HTML helpers are more lightweight compared to web controls as
it does not hold viewstate and events.

HTML Helpers returns the HTML string which can be directly


rendered to HTML page. Custom HTML Helpers also can be
created by overriding “HtmlHelper” class.

23) What are AJAX Helpers in MVC?

AJAX Helpers are used to create AJAX enabled elements like as


Ajax enabled forms and links which performs the request
asynchronously and these are extension methods of AJAXHelper
class which exists in namespace — System.Web.Mvc.

24) What are the options can be configured in AJAX


helpers?
Below are the options in AJAX helpers –

Url — This is the request URL.

Confirm — This is used to specify the message which is to be


displayed in confirm box.

OnBegin — Javascript method name to be given here and this will


be called before the AJAX request.

OnComplete — Javascript method name to be given here and this


will be called at the end of AJAX request.

OnSuccess — Javascript method name to be given here and this


will be called when AJAX request is successful.

OnFailure — Javascript method name to be given here and this


will be called when AJAX request is failed.

UpdateTargetId — Target element which is populated from the


action returning HTML.

25) What is Layout in MVC?

Layout pages are similar to master pages in traditional web forms.


This is used to set the common look across multiple pages. In each
child page we can find — /p>

@{

Layout = “~/Views/Shared/TestLayout1.cshtml”;
}

This indicates child page uses TestLayout page as it’s master page.

26) Explain Sections is MVC?

Section are the part of HTML which is to be rendered in layout


page. In Layout page we will use the below syntax for rendering
the HTML –

@RenderSection(“TestSection”)

And in child pages we are defining these sections as shown below


@section TestSection{

<h1>Test Content</h1>

If any child page does not have this section defined then error will
be thrown so to avoid that we can render the HTML like this –

@RenderSection(“TestSection”, required: false)

27) Can you explain RenderBody and RenderPage in


MVC?

RenderBody is like ContentPlaceHolder in web forms. This will


exist in layout page and it will render the child pages/views.
Layout page will have only one RenderBody() method.
RenderPage also exists in Layout page and multiple RenderPage()
can be there in Layout page.

28) What is ViewStart Page in MVC?

This page is used to make sure common layout page will be used
for multiple views. Code written in this file will be executed first
when application is being loaded.

29) Explain the methods used to render the views in


MVC?

Below are the methods used to render the views from action -

View() — To return the view from action.

PartialView() — To return the partial view from action.

RedirectToAction() — To Redirect to different action which can be


in same controller or in different controller.

Redirect() — Similar to “Response.Redirect()” in webforms, used


to redirect to specified URL.

RedirectToRoute() — Redirect to action from the specified URL


but URL in the route table has been matched.

30) What are the sub types of ActionResult?

ActionResult is used to represent the action method result. Below


are the subtypes of ActionResult –
ViewResult

PartialViewResult

RedirectToRouteResult

RedirectResult

JavascriptResult

JSONResult

FileResult

HTTPStatusCodeResult

31) What are Non Action methods in MVC?

In MVC all public methods have been treated as Actions. So if you


are creating a method and if you do not want to use it as an action
method then the method has to be decorated with “NonAction”
attribute as shown below –

[NonAction]

public void TestMethod()

// Method logic
}

32) How to change the action name in MVC?

“ActionName” attribute can be used for changing the action name.


Below is the sample code snippet to demonstrate more –

[ActionName(“TestActionNew”)]

public ActionResult TestAction()

return View();

So in the above code snippet “TestAction” is the original action


name and in “ActionName” attribute, name — “TestActionNew” is
given. So the caller of this action method will use the name
“TestActionNew” to call this action.

33) What are Code Blocks in Views?

Unlike code expressions that are evaluated and sent to the


response, it is the blocks of code that are executed. This is useful
for declaring variables which we may be required to be used later.

@{

int x = 123;
string y = “aa”;

34) What is the “HelperPage.IsAjax” Property?

The HelperPage.IsAjax property gets a value that indicates


whether Ajax is being used during the request of the Web page.

35) How we can call a JavaScript function on the change


of a Dropdown List in MVC?

Create a JavaScript method:

<script type=”text/javascript”>

function DrpIndexChanged() { }

</script>

Invoke the method:

<%:Html.DropDownListFor(x => x.SelectedProduct, new


SelectList(Model.Customers, “Value”, “Text”), “Please Select a
Customer”, new { id = “ddlCustomers”, onchange=”
DrpIndexChanged ()” })%>

36) What are Validation Annotations?

Data annotations are attributes which can be found in the


“System.ComponentModel.DataAnnotations” namespace. These
attributes will be used for server-side validation and client-side
validation is also supported. Four attributes — Required, String
Length, Regular Expression and Range are used to cover the
common validation scenarios.

37) Why to use Html.Partial in MVC?

This method is used to render the specified partial view as an


HTML string. This method does not depend on any action
methods. We can use this like below –

@Html.Partial(“TestPartialView”)

38) What is Html.RenderPartial?

Result of the method — “RenderPartial” is directly written to the


HTML response. This method does not return anything (void).
This method also does not depend on action methods.
RenderPartial() method calls “Write()” internally and we have to
make sure that “RenderPartial” method is enclosed in the bracket.
Below is the sample code snippet
–@{Html.RenderPartial(“TestPartialView”); }

39) What is RouteConfig.cs in MVC 4?

“RouteConfig.cs” holds the routing configuration for MVC.


RouteConfig will be initialized on Application_Start event
registered in Global.asax.

40) What are Scaffold templates in MVC?


Scaffolding in ASP.NET MVC is used to generate the
Controllers,Model and Views for create, read, update, and delete
(CRUD) functionality in an application. The scaffolding will be
knowing the naming conventions used for models and controllers
and views.

41) Explain the types of Scaffoldings.

Below are the types of scaffoldings –

Empty

Create

Delete

Details

Edit

List

42) Can a view be shared across multiple controllers? If


Yes, How we can do that?

Yes, we can share a view across multiple controllers. We can put


the view in the “Shared” folder. When we create a new MVC
Project we can see the Layout page will be added in the shared
folder, which is because it is used by multiple child pages.

43) What are the components required to create a route


in MVC?
Name — This is the name of the route.

URL Pattern — Placeholders will be given to match the request


URL pattern.

Defaults –When loading the application which controller, action


to be loaded along with the parameter.

44) Why to use “{resource}.axd/{*pathInfo}” in routing


in MVC?

Using this default route — {resource}.axd/{*pathInfo}, we can


prevent the requests for the web resources files like —
WebResource.axd or ScriptResource.axd from passing to a
controller.

45) Can we add constraints to the route? If yes, explain


how we can do it?

Yes we can add constraints to route in following ways –

Using Regular Expressions

Using object which implements interface — IRouteConstraint.

46) What are the possible Razor view extensions?

Below are the two types of extensions razor view can have –

.cshtml — In C# programming language this extension will be


used.
.vbhtml — In VB programming language this extension will be
used.

47) What is PartialView in MVC?

PartialView is similar to UserControls in traditional web forms.


For re-usability purpose partial views are used. Since it’s been
shared with multiple views these are kept in shared folder. Partial
Views can be rendered in following ways –

Html.Partial()

Html.RenderPartial()

48) How we can add the CSS in MVC?

Below is the sample code snippet to add css to razor views –

<link rel=”StyleSheet” href=”/@Href(~Content/Site.css”)”


type=”text/css”/>

49) Can I add MVC Testcases in Visual Studio Express?

No. We cannot add the test cases in Visual Studio Express edition
it can be added only in Professional and Ultimate versions of
Visual Studio.
50) What is the use .Glimpse in MVC?

Glimpse is an open source tool for debugging the routes in MVC.


It is the client side debugger. Glimpse has to be turned on by
visiting to local url link

1) What is MVC (Model view controller)?

Model-View-Controller (MVC) is a software architectural pattern for implementing user


interfaces. It divides a given software application into three interconnected parts, to
separate the internal representation of information from the way that information is
presented to or accepted by the user.

2) What is Razor in MVC?

Razor is a view engine that lets you embed server-based code into web pages using C#
and VB.Net. It was introduced in MVC 3 and a gneral purpose templating engine.

3) Explain attribute based routing in MVC?

Routing is the process of monitoring the requests with the MVC application. In MVC,
the Application_Start() event registers all the routes in the routing table.

In ASP.NET MVC 5.0, a new type of routing is introduced, it is called Attribute Routing.
It enables the developers to define the routing using attributes on top of the controller
action method. To use the attribute routing in the MVC 5, you need to call the
MapMvcAttributeRoute method. The optional parameter for the URI can be added to the
route parameter using the question mark(?) in the attribute routing.
4) What is TempData in MVC?

The TempData in the ASP.NET MVC is used to store temporary data. It can be used in
subsequent requests. This TempData will be cleared after the completion of the
subsequent request. It is useful in transferring the non-sensitive data from one action
method to another action method of the same or a different controller and redirects. It
stores data as key-value pair.

Example

public ActionResult Index()


{
TempData["name"] = "Test data";
}
public ActionResult About()
{
string userName;
if(TempData.ContainsKey("name"))
userName = TempData["name"].ToString();
}

5) What is Partial View in MVC?

A partial view is a chunk of HTML that can be safely inserted into an existing DOM.
Most commonly, partial views are used to componentize Razor views and make them
easier to build and update. Partial views can also be returned directly from controller
methods. In this case, the browser still receives text/HTML content but not necessarily
HTML content that makes up an entire page. As a result, if a URL that returns a partial
view is directly invoked from the address bar of a browser, an incomplete page may be
displayed. This may be something like a page that misses title, script and style sheets.

Download Free : MVC interview questions PDF

6) Mention what is the difference between ViewData and ViewBag?


In ASP.NET MVC there are three ways to pass/store data between the controllers and
views.

ViewData

1. ViewData is used to pass data from a controller to view.


2. It is derived from ViewDataDictionary class.
3. It is available for the current request only.
4. Requires typecasting for complex data type and checks for null values to avoid error.
5. If redirection occurs, then its value becomes null.

ViewBag

1. ViewBag is also used to pass data from the controller to the respective view.
2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C#
4.0
3. It is also available for the current request only.
4. If redirection occurs, then its value becomes null.
5. Doesn’t require typecasting for the complex data type.

7) What is Route in MVC?

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. A handler can also be a class that
processes the request, such as a controller in an MVC application. To define a route,
you create an instance of the route class by specifying the URL pattern, the handler,
and optionally a name for the route.

8) Explain what is routing in MVC?

Routing is a mechanism to process the incoming URL that is more descriptive and gives
the desired response. In this case, URL is not mapped to specific files or folder, as was
the case of websites in the past.

9) What are the three segments for routing important?


Routing is the URL pattern that is mapped together to a handler and is responsible for
incoming browser request for a particular MVC controller. There are a total of three
segments for routing that are very significant in MVC

1. ControllerName
2. ActionMethodName
3. Parammeter

10) What are the Filters in MVC?

The filter in ASP.NET MVC is a class that is executed before or after an action method
is executed. It is a place where you can write custom logic that you want to execute. It
can be executed either to an action method or a controller. It is applied in two different
ways, declarative and programmatic. Applying the filter to the action or controller class
is called a declarative filter. Defining the interface for the filter is called the programmatic
way of applying a filter.

There are four types of built-in filters in ASP.NET MVC are authorization filter, action
filter, result filter, exception filter. These filters give an interface for which you can
define your custom filter.

Take Free: Mvc MCQ & Quiz

11) What are Action Filters in MVC?

An action filter is a type of filter in ASP.NET MVC that is executed to implement logic
before and after a controller is executed. These provide an additional attribute that is
applied to a section of the controller or the whole controller to modify it. These attributes
are defined under System.Attribute class.

Three types of action filters in ASP.NET MVC are,

● Output cache – It caches the output of a controller action. The output is cached here for
a defined amount of time.
● Handle Error – This filter is used to handle errors from the execution of controller action.
● Authorize – This filter is used to restrict access to the action method for a particular
user.

12) What are the types of filters?


ASP.NET MVC structure upholds the following action filters:

● Action Filters: Action filters are used to implement logic that gets executed before and
after a controller action executes. We will look at Action Filters in detail in this chapter.
● Authorization Filters: Authorization filters are used to implement authentication and
authorization for controller actions.
● Result Filters: 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: 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 can also use exception filters to log errors.

13) List the various return types of a controller action method.

There is total of nine return types we can use to return results from a controller to view.
The base type of all these result types is ActionResult.

1. ViewResult (View): This return type is used to return a webpage from an action method.
2. PartialviewResult (Partialview): This return type is used to send a part of a view that
will be rendered in another view.
3. RedirectResult (Redirect): This return type is used to redirect to any other controller
and action method depending on the URL.
4. RedirectToRouteResult (RedirectToAction, RedirectToRoute): This return type is
used when we want to redirect to any other action method.
5. ContentResult (Content): This return type is used to return HTTP content type like
text/plain as the result of the action.
6. jsonResult (JSON): This return type is used when we want to return a JSON message.
7. javascriptResult (javascript): This return type is used to return JavaScript code that
will run in the browser.
8. FileResult (File): This return type is used to send binary output in response.
9. EmptyResult: This return type is used to return nothing (void) in the result.

14) Explain what is MVC application life cycle?

Any web application has two main execution steps, first understanding the request and
depending on the type of the request sending out an appropriate response. MVC
application life cycle is not different it has two main phases, first creating the request
object and second sending our response to the browser.

Creating the request object includes four basic steps:


Step 1: Fill route
Step 2: Fetch route
Step 3: Request context created
Step 4: Controller instance created

15) What are the advantages of MVC?

Benefits or advantages of MVC are as follows:

● Multiple view support: Due to the separation of the model from the view, the user
interface can display multiple views of the same data at the same time.
● Change Accommodation: User interfaces tend to change more frequently than
business rules (different colors, fonts, screen layouts, and levels of support for new
devices such as cell phones or PDAs)
● SoC – Separation of Concerns: Separation of Concerns is one of the core advantages of
ASP.NET MVC. The MVC framework provides a clean separation of the UI, Business
Logic, Model or Data.
● More Control: The ASP.NET MVC framework provides more control over HTML,
JavaScript, and CSS than the traditional Web Forms.
● Testability: ASP.NET MVC framework provides better testability of the Web Application
and good support for the test-driven development too.
● Lightweight: ASP.NET MVC framework doesn’t use View State and thus reduces the
bandwidth of the requests to an extent.

1) What is MVC (Model view controller)?

Model-View-Controller (MVC) is a software architectural pattern for implementing user


interfaces. It divides a given software application into three interconnected parts, to
separate the internal representation of information from the way that information is
presented to or accepted by the user.
2) What is Razor in MVC?
Razor is a view engine that lets you embed server-based code into web pages using C# and
VB.Net. It was introduced in MVC 3 and a gneral purpose templating engine.

3) Explain attribute based routing in MVC?

Routing is the process of monitoring the requests with the MVC application. In MVC,
the Application_Start() event registers all the routes in the routing table.

In ASP.NET MVC 5.0, a new type of routing is introduced, it is called Attribute Routing.
It enables the developers to define the routing using attributes on top of the controller
action method. To use the attribute routing in the MVC 5, you need to call the
MapMvcAttributeRoute method. The optional parameter for the URI can be added to the
route parameter using the question mark(?) in the attribute routing.

4) What is TempData in MVC?


The TempData in the ASP.NET MVC is used to store temporary data. It can be used in
subsequent requests. This TempData will be cleared after the completion of the
subsequent request. It is useful in transferring the non-sensitive data from one action
method to another action method of the same or a different controller and redirects. It
stores data as key-value pair.

Example

public ActionResult Index()


{
TempData["name"] = "Test data";
}
public ActionResult About()
{
string userName;
if(TempData.ContainsKey("name"))
userName = TempData["name"].ToString();
}
5) What is Partial View in MVC?

A partial view is a chunk of HTML that can be safely inserted into an existing DOM.
Most commonly, partial views are used to componentize Razor views and make them
easier to build and update. Partial views can also be returned directly from controller
methods. In this case, the browser still receives text/HTML content but not necessarily
HTML content that makes up an entire page. As a result, if a URL that returns a partial
view is directly invoked from the address bar of a browser, an incomplete page may be
displayed. This may be something like a page that misses title, script and style sheets.

6) Mention what is the difference between ViewData and ViewBag?


In ASP.NET MVC there are three ways to pass/store data between the controllers and
views.

ViewData

1. ViewData is used to pass data from a controller to view.


2. It is derived from ViewDataDictionary class.
3. It is available for the current request only.
4. Requires typecasting for complex data type and checks for null values to avoid
error.
5. If redirection occurs, then its value becomes null.

ViewBag

1. ViewBag is also used to pass data from the controller to the respective view.
2. ViewBag is a dynamic property that takes advantage of the new dynamic
features in C# 4.0
3. It is also available for the current request only.
4. If redirection occurs, then its value becomes null.
5. Doesn’t require typecasting for the complex data type.

7) What is Route in MVC?


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. A handler can also be a class that processes the
request, such as a controller in an MVC application. To define a route, you create an instance of
the route class by specifying the URL pattern, the handler, and optionally a name for the route.
8) Explain what is routing in MVC?
Routing is a mechanism to process the incoming URL that is more descriptive and gives the
desired response. In this case, URL is not mapped to specific files or folder, as was the case of
websites in the past.

9) What are the three segments for routing important?

Routing is the URL pattern that is mapped together to a handler and is responsible for
incoming browser request for a particular MVC controller. There are a total of three
segments for routing that are very significant in MVC

1. ControllerName
2. ActionMethodName
3. Parammeter

10) What are the Filters in MVC?

The filter in ASP.NET MVC is a class that is executed before or after an action method
is executed. It is a place where you can write custom logic that you want to execute. It
can be executed either to an action method or a controller. It is applied in two different
ways, declarative and programmatic. Applying the filter to the action or controller class
is called a declarative filter. Defining the interface for the filter is called the programmatic
way of applying a filter.

There are four types of built-in filters in ASP.NET MVC are authorization filter, action
filter, result filter, exception filter. These filters give an interface for which you can
define your custom filter.

Take Free: Mvc MCQ & Quiz

11) What are Action Filters in MVC?

An action filter is a type of filter in ASP.NET MVC that is executed to implement logic
before and after a controller is executed. These provide an additional attribute that is
applied to a section of the controller or the whole controller to modify it. These attributes
are defined under System.Attribute class.

Three types of action filters in ASP.NET MVC are,

● Output cache – It caches the output of a controller action. The output is cached here for
a defined amount of time.
● Handle Error – This filter is used to handle errors from the execution of controller action.
● Authorize – This filter is used to restrict access to the action method for a particular
user.

12) What are the types of filters?

ASP.NET MVC structure upholds the following action filters:

● Action Filters: Action filters are used to implement logic that gets executed before and
after a controller action executes. We will look at Action Filters in detail in this chapter.
● Authorization Filters: Authorization filters are used to implement authentication and
authorization for controller actions.
● Result Filters: 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: 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 can also use exception filters to log errors.

13) List the various return types of a controller action method.

There is total of nine return types we can use to return results from a controller to view.
The base type of all these result types is ActionResult.

1. ViewResult (View): This return type is used to return a webpage from an action method.
2. PartialviewResult (Partialview): This return type is used to send a part of a view that
will be rendered in another view.
3. RedirectResult (Redirect): This return type is used to redirect to any other controller
and action method depending on the URL.
4. RedirectToRouteResult (RedirectToAction, RedirectToRoute): This return type is
used when we want to redirect to any other action method.
5. ContentResult (Content): This return type is used to return HTTP content type like
text/plain as the result of the action.
6. jsonResult (JSON): This return type is used when we want to return a JSON message.
7. javascriptResult (javascript): This return type is used to return JavaScript code that
will run in the browser.
8. FileResult (File): This return type is used to send binary output in response.
9. EmptyResult: This return type is used to return nothing (void) in the result.

14) Explain what is MVC application life cycle?

Any web application has two main execution steps, first understanding the request and
depending on the type of the request sending out an appropriate response. MVC
application life cycle is not different it has two main phases, first creating the request
object and second sending our response to the browser.

Creating the request object includes four basic steps:

Step 1: Fill route


Step 2: Fetch route
Step 3: Request context created
Step 4: Controller instance created

15) What are the advantages of MVC?

Benefits or advantages of MVC are as follows:

● Multiple view support: Due to the separation of the model from the view, the user
interface can display multiple views of the same data at the same time.
● Change Accommodation: User interfaces tend to change more frequently than
business rules (different colors, fonts, screen layouts, and levels of support for new
devices such as cell phones or PDAs)
● SoC – Separation of Concerns: Separation of Concerns is one of the core advantages of
ASP.NET MVC. The MVC framework provides a clean separation of the UI, Business
Logic, Model or Data.
● More Control: The ASP.NET MVC framework provides more control over HTML,
JavaScript, and CSS than the traditional Web Forms.
● Testability: ASP.NET MVC framework provides better testability of the Web Application
and good support for the test-driven development too.
● Lightweight: ASP.NET MVC framework doesn’t use View State and thus reduces the
bandwidth of the requests to an extent.
16) What does the MVC pattern define with 3 logical layers?

The MVC model defines web applications with 3 logic layers:

● The business layer (Model logic)


● The display layer (View logic)
● The input control (Controller logic)

The Model is the part of the application, which only handles the logic for the application
data. Regularly, the model objects retrieve data (as well as store data) from a database.
The View is the part of the application, which takes care of the display of the data.

Most often, the views are created from the model data, although there are other, more
complicated methods of creating views.

The Controller, as the name implies, is the part of the application that handles user
interaction.

17) What is Default Route in MVC?

Default Route: The default ASP.NET MVC project templates add a generic route that
uses the following URL convention to break the URL for a given request into three
named segments.

URL: "{controller}/{action}/{id}"
This route pattern is registered via a call to the MapRoute() extension method
of RouteCollection.

18) What are HTML helpers in MVC?

In MVC HTML Helpers is a class which are used in views to render/display HTML
controls like links, TextBox, TextArea, etc.

HTML Helper Example in MVC

@Html.ActionLink("Create New", "create")


The above example generates an HTML link something like <a href="/create">Create
New</a>
19) Define attribute based routing in MVC?

Attribute Routing was introduced in ASP.NET MVC 5. It allows developers to generate


urls for controllers actions by adding Route Attributes to them.

This type of MVC routing uses attributes to define routes and gives developer more
control over the urls of web application.In order to use Attribute Routing first you have to
enable it by calling MapMvcAttributeRoutes during configuration.

//Configuring Attribute Routing in MVC.

public class RouteConfig


{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapMvcAttributeRoutes();
}
}

20) What are the Main Razor Syntax Rules?

Following are the rules for main Razor Syntax:

● Razor code blocks are enclosed in @{ … }


● Inline expressions (variables and functions) start with @
● Code statements end with a semicolon
● Variables are declared with the var keyword
● Strings are enclosed with quotation marks
● C# code is case sensitive
● C# files have the extension .cshtml

21) How do you implement Forms authentication in MVC

Authentication is giving access to the user for a specific service by verifying his/her
identity using his/her credentials like username and password or email and password. It
assures that the correct user is authenticated or logged in for a specific service and the
right service has been provided to the specific user based on their role that is nothing
but authorization.
22) What are the Benefits of Area in MVC?

Benefits of Area in MVC

1. Allows us to organize models, views, and controllers into separate functional sections of
the application, such as administration, billing, customer support and much more.
2. Easy to integrate with other Areas created by another.
3. Easy for unit testing.

23) Explain the need of display mode in MVC?

A display mode is a powerful tool for all mobile-based apps development. However, it is
not limited to mobile web apps but it can also be used to display any alternative view,
which is tied to an existing controller. Display Modes practically give you another level of
flexibility on top of the default capabilities we saw in the last section. Display Modes can
also be used along with the previous feature so the users will simply build off of the site
they just created. It simplifies the ways to implement different versions of view for
different devices.

24) Explain the concept of MVC Scaffolding?

ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications.


Visual Studio 2013 includes pre-installed code generators for MVC and Web API
projects. You add scaffolding to your project when you want to quickly add code that
interacts with data models. Using scaffolding can reduce the amount of time to develop
standard data operations in your project.
Scaffolding consists of page templates, entity page templates, field page templates, and
filter templates. These templates are called Scaffold templates and allow you to quickly
build a functional data-driven Website.

25) What are Route Constraints in MVC?

Route constraints in the ASP.NET are used to control the behavior of the route. With
route constraint, you can restrict your users to a set of URLs, or restrict browser
requests to match a particular route. The route constraints are defined by using a
regular expression. For eg: to set a constraint string to our hostname, we can use the
routing constraint as the following. Open the RouteConfig.cs file and modify the routing
entry as "abc/{controller}/{action}/{id}". Now the URL with string "abc" as the prefix will
only be able to access the site.

26) What is Output Caching in MVC?

The Output cache in the ASP.NET MVC will increase the performance of your
application significantly. It is used to cache the value that is returned by the controller
action. So, when every time the controller action is invoked, the same value need not be
generated each time. To enable the output cache, use the OutputCache attribute to the
individual controller action or the entire controller class. You can also define the duration
for the content to be cached in the output cache.

Example:

using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
[HandleError]
public class HomeController : Controller
{
[OutputCache(Duration=10, VaryByParam="none")]
public ActionResult Index()
{
return View();
}
}
}

In the above example, the output view is cached in the output cache for about 10
seconds.

27) What is Bundling and Minification in MVC?

Bundling and minification are two new techniques introduced to improve request load
time. It improves load time by reducing the number of requests to the server and
reducing the size of requested assets (such as CSS and JavaScript).

Bundling: It lets us combine multiple JavaScript (.js) files or multiple cascading style
sheet (.css) files so that they can be downloaded as a unit, rather than making
individual HTTP requests.
Minification: It extracts the whitespace and performs other types of compression to
make the downloaded files as small as possible. At runtime, the process recognizes the
agent of the user, for example, IE, Mozilla, etc. and then removes whatever is specific to
Mozilla when the request comes from IE.

28) What is Validation Summary in MVC?

The Validation Summary helper method generates an unordered list (UL element) of
validation messages that are in the Model State Dictionary object.

The Validation Summary can be used to display all the error messages for all the fields.
It can also be used to display custom error messages. The following figure shows how
Validation Summary displays the error messages.

29) Explain what is Database First Approach in MVC using Entity Framework?

Database First Approach is an alternative or substitutes to the Code First and Model
First approaches to the Entity Data Model. The Entity Data Model creates model codes
(classes, properties, DbContext, etc.) from the database in the project and that class
behaves as the link between database and controller.

There are the following approaches, which are used to connect the database with the
application.

● Database First
● Model First
● Code First

30) What is GET and POST Actions Types?

GET Action Type: GET is used to request data from a specified resource. With all the
GET requests, we pass the URL, which is compulsory; however, it can take up the
following overloads.

POST Action Type: Tthe POST is used to submit data to be processed to a specified
resource. With all the POST requests, we pass the URL, which is essential and the
data. However, it can take up the following overloads.
31) What’s new in the latest version of MVC?

In MVC 6 Microsoft removed the dependency of System.Web.Dll from MVC6 because it


is extremely expensive, as it typically used to consume 30K of memory per request and
response, whereas now MVC 6 only requires 2K of memory per request and the
response is really small memory consumption.

32) How to render raw html in Asp.net MVC view?

You can use Html.Raw helper to render raw Html in Asp.net MVC

Syntax

@Html.Raw('<h1>Raw Example </h1>');

You might also like