0% found this document useful (0 votes)
60 views12 pages

MVC Interview Questions

MVC Interview Questions
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views12 pages

MVC Interview Questions

MVC Interview Questions
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Q. What is MVC?

Ans. MVC stands for Model-View-Controller. It is a software design pattern which was introduced in
1970s. Also, MVC pattern forces a separation of concerns, it means domain model and controller logic
are decoupled from user interface (view). As a result maintenance and testing of the application become
simpler and easier.

Q. Explain MVC design pattern?


Ans. MVC design pattern splits an application into three main aspects: Model, View and Controller.

Model - The Model represents a set of classes that describe the business logic i.e. business model as
well as data access operations i.e. data model. It also defines business rules for data means how the
data can be changed and manipulated.

View - The View represents the UI components like CSS, jQuery, html etc. It is only responsible for
displaying the data that is received from the controller as the result. This also transforms the model(s)
into UI.

Controller - The Controller is responsible to process incoming requests. It receives input from users via
the View, then process the user's data with the help of Model and passing the results back to the View.
Typically, it acts as the coordinator between the View and the Model.

Q. What is MVP pattern?


Ans. This pattern is similar to MVC pattern in which controller has been replaced by the presenter. This
design pattern splits an application into three main aspects: Model, View and Presenter.

Model - The Model represents a set of classes that describes the business logic and data. It also defines
business rules for data means how the data can be changed and manipulated.

View - The View represents the UI components like CSS, jQuery, html etc. It is only responsible for
displaying the data that is received from the presenter as the result. This also transforms the model(s)
into UI.

Presenter - The Presenter is responsible for handling all UI events on behalf of the view. This receive
input from users via the View, then process the user's data with the help of Model and passing the
results back to the View. Unlike view and controller, view and presenter are completely decoupled from
each other’s and communicate to each other’s by an interface.
Also, presenter does not manage the incoming request traffic as controller.

This pattern is commonly used with ASP.NET Web Forms applications which require to create
automated unit tests for their code-behind pages. This is also used with windows forms.

Key Points about MVP Pattern

1. User interacts with the View.


2. There is one-to-one relationship between View and Presenter means one View is mapped to only one
Presenter.
3. View has a reference to Presenter but View has not reference to Model.
4. Provides two way communications between View and Presenter.

Q. What is MVVM pattern?


Ans. MVVM stands for Model-View-View Model. This pattern supports two-way data binding between
view and View model. This enables automatic propagation of changes, within the state of view model to
the View. Typically, the view model uses the observer pattern to notify changes in the view model to
model.
Model - The Model represents a set of classes that describes the business logic and data. It also defines
business rules for data means how the data can be changed and manipulated.

View - The View represents the UI components like CSS, jQuery, html etc. It is only responsible for
displaying the data that is received from the controller as the result. This also transforms the model(s)
into UI.

View Model - The View Model is responsible for exposing methods, commands, and other properties
that help to maintain the state of the view, manipulate the model as the result of actions on the view,
and trigger events in the view itself.

This pattern is commonly used by the WPF, Silverlight, Caliburn, nRoute etc.

Key Points about MVVM Pattern

1. User interacts with the View.


2. There is many-to-one relationship between View and ViewModel means many View can be mapped
to one ViewModel.
3. View has a reference to ViewModel but View Model has no information about the View.
4. Supports two-way data binding between View and ViewModel.

Q. How MVC pattern works in ASP.NET MVC?


Ans. Working of MVC pattern in ASP.NET MVC is explained as below:

The Model in ASP.NET MVC


The Model in ASP.NET MVC can be broken down into several different layers as given below:
1. Objects or ViewModel or Presentation Layer - This layer contains simple objects or complex objects
which are used to specify strongly-typed view. These objects are used to pass data from controller to
strongly-typed view and vice versa. The classes for these objects can have specific validation rules which
are defined by using data annotations. Typically, these classes have those properties which you want to
display on corresponding view/page.

2. Business Layer - This layer helps you to implement your business logic and validations for your
application. This layer makes use of Data Access Layer for persisting data into database. Also, this layer is
directly invoked by the Controller to do processing on input data and sent back to view.
3. Data Access Layer - This layer provides objects to access and manipulate the database of your
application. Typically, this layer is made by using ORM tools like Entity Framework or NHibernate etc.

The View in ASP.NET MVC


The view is only responsible for displaying the data that is received from the controller as a result. It also
responsible for transforming a model or models into UI which provide all the required business logic and
validation to the view.
By default, views are stored in the Views folder of an ASP.NET MVC application.

The Controller in ASP.NET MVC


The Controller in ASP.NET MVC, respond to HTTP requests and determine the action to take based upon
the content of the incoming request. It receives input from users via the View, then process the user's
data with the help of Model and passing the results back to the View.
By default, controllers are stored in the Controllers folder in ASP.NET MVC application.

Q. How Model, View and Controller communicate with each other in ASP.NET
MVC?
Ans. There are following rules for communication among Model, View and Controller:
1. User interacts with the Controller.
2. There is one-to-many relationship between Controller and View means one controller can mapped to
multiple views.
3. Controller and View can have a reference to model.
4. Controller and View can talk to each other.
5. Model and View cannot talk to each other directly. They communicate to each other with the help of
controller.

Q. What are advantages of ASP.NET MVC?


Ans. There are following advantages of ASP.NET MVC over Web Forms (ASP.NET):
 Separation of concern - MVC design pattern divides the ASP.NET MVC application into three main
aspects Model, View and Controller which make it easier to manage the application complexity.
 TDD - The MVC framework brings better support to test-driven development.
 Extensible and pluggable - MVC framework components were designed to be pluggable and
extensible and therefore can be replaced or customized easier then Web Forms.
 Full control over application behavior - MVC framework doesn’t use View State or server based forms
like Web Forms. This gives the application developer more control over the behaviors of the application
and also reduces the bandwidth of requests to the server.
 ASP.NET features are supported - MVC framework is built on top of ASP.NET and therefore can use
most of the features that ASP.NET include such as the providers architecture, authentication and
authorization scenarios, membership and roles, caching, session and more.
 URL routing mechanism - MVC framework supports a powerful URL routing mechanism that helps to
build a more comprehensible and searchable URLs in your application. This mechanism helps to the
application to be more addressable from the eyes of search engines and clients and can help in search
engine optimization.
Q. What is difference between 3-layer architecture and MVC architecture?
Ans. 3-layer architecture separates the application into 3 components which consists of Presentation
Layer Business Layer and Data Access Layer. In 3-layer architecture, user interacts with the Presentation
layer. 3-layer is a linear architecture.

MVC architecture separates the application into three components which consists of Model, View and
Controller. In MVC architecture, user interacts with the controller with the help of view. MVC is triangle
architecture.

MVC does not replace 3-layer architecture. Typically 3-layer and MVC are used together and MVC acts as
the Presentation layer.

Q. What is difference between ASP.NET WebForm and ASP.NET MVC?


Ans. The main differences between ASP.NET Web Form and ASP.NET MVC are given below: ASP.NET

Web Forms ASP.NET MVC


ASP.NET Web Form follows a traditional event driven ASP.NET MVC is a lightweight and follow MVC
development model. (Model, View, and Controller) pattern based
development model.
ASP.NET Web Form has server controls. ASP.NET MVC has html helpers.
ASP.NET Web Form has state management (like as ASP.NET MVC has no automatic state management
view state, session) techniques. techniques.
ASP.NET Web Form has file-based URLs means file ASP.NET MVC has route-based URLs means URLs are
name exist in the URLs must have its physically divided into controllers and actions and moreover it
existence. is based on controller not on physical file.
ASP.NET Web Form follows WebForm Syntax ASP.NET MVC follow customizable syntax (Razor as
default)
In ASP.NET Web Form, Web Forms (ASPX) i.e. views In ASP.NET MVC, Views and logic are kept separately.
are tightly coupled to Code behind (ASPX.CS) i.e.
logic.
ASP.NET Web Form has Master Pages for consistent ASP.NET MVC has Layouts for consistent look and
look and feels. feels.
ASP.NET Web Form has User Controls for code re- ASP.NET MVC has Partial Views for code re-usability.
usability.
ASP.NET Web Form has built-in data controls and ASP.NET MVC is lightweight, provide full control over
best for rapid development with powerful data mark-up and support many features that allow fast &
access. agile development. Hence it is best for developing
interactive web application with latest web
standards.
ASP.NET Web Form is not Open Source. ASP.NET Web MVC is an Open Source.

Q. What is ViewModel in ASP.NET MVC?


Ans. In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in the
strongly-typed view. It is used to pass data from controller to strongly-typed view.
Key Points about ViewModel
 ViewModel contain fields that are represented in the view (for LabelFor, EditorFor, DisplayFor helpers)
 ViewModel can have specific validation rules using data annotations.
 ViewModel can have multiple entities or objects from different data models or data source.

Q. What is Routing in ASP.NET MVC?


Ans. Routing is a pattern matching system that monitors the incoming request and figure out what to do
with that request. At runtime, Routing engine use the Route table for matching the incoming request's
URL pattern against the URL patterns defined in the Route table. You can register one or more URL
patterns to the Route table at Application_Start event.
When the routing engine finds a match in the route table for the incoming request's URL, it forwards the
request to the appropriate controller and action. If there is no match in the route table for the incoming
request's URL, it returns a 404 HTTP status code.

Q. What is Attribute Routing and how to define it?


Ans. ASP.NET MVC5 and WEB API 2 supports a new type of routing, called attribute routing. In this
routing, attributes are used to define routes. Attribute routing provides you more control over the URIs
by defining routes directly on actions and controllers in your ASP.NET MVC application and WEB API.

1. Controller level routing – You can define routes at controller level which apply to all actions within
the controller unless a specific route is added to an action.

[RoutePrefix("MyHome")]
[Route("{action=index}")] //default action
public class HomeController : Controller
{
//new route: /MyHome/Index
public ActionResult Index()
{
return View();
}
//new route: /MyHome/About
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
//new route: /MyHome/Contact
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}

2. Action level routing – You can define routes at action level which apply to a specific action within the
controller.

public class HomeController : Controller


{
[Route("users/{id:int:min(100)}")] //route: /users/100
public ActionResult Index(int id)
{
//TO DO:
return View();
}
[Route("users/about")] //route" /users/about
public ActionResult About()
{
ViewBag.Message = "Your application description page.";

return View();
}
//route: /Home/Contact
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}

Note:
 Attribute routing should configure before the convention-based routing.
 When you combine attribute routing with convention-based routing, actions which do not have Route
attribute for defining attribute-based routing will work according to convention-based routing. In above
example Contact action will work according to convention-based routing.
 When you have only attribute routing, actions which do not have Route attribute for defining
attribute-based routing will not be the part of attribute routing. In this way they can’t be access from
outside as a URI.
Q19. How to enable Attribute Routing in ASP.NET MVC?
Ans. Enabling attribute routing in your ASP.NET MVC5 application is simple, just add a call to
routes.MapMvcAttributeRoutes() method with in RegisterRoutes() method of RouteConfig.cs file.

public class RouteConfig


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

//enabling attribute routing


routes.MapMvcAttributeRoutes();
}
}

You can also combine attribute routing with convention-based routing.

public class RouteConfig


{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//enabling attribute routing
routes.MapMvcAttributeRoutes();
//convention-based routing
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional });
}
}

Q. What is Route Constraints in ASP.NET MVC?


Ans. Route constraints are way to put some validation around the defined route.
Creating Route Constraints
Suppose we have defined the following route in our application and you want to restrict the incoming
request URL with numeric id only. Now let's see how to do it with the help of regular expression.

public static void RegisterRoutes(RouteCollection routes)


{
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // Route Pattern
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
} // Default values for parameters
);
}

Restrict to numeric id only

public static void RegisterRoutes(RouteCollection routes)


{
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // Route Pattern
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}, // Default values for parameters
new { id = @"\d+" } //Restriction for id
);
}

Q. How route table is created in ASP.NET MVC?


Ans. When an MVC application first starts, the Application_Start() method in global.asax is called. This
method calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table for
MVC application.

Q. What are HTML Helpers in ASP.NET MVC?


Ans. An HTML Helper is just a method that returns a HTML string. The string can represent any type of
content that you want. For example, you can use HTML Helpers to render standard HTML tags like
HTML <input>, <button> and <img> tags etc.
You can also create your own HTML Helpers to render more complex content such as a menu strip or an
HTML table for displaying database data.

Q. What are Layouts in ASP.NET MVC?


Ans. Layouts are used to maintain a consistent look and feel across multiple views within ASP.NET MVC
application. As compared to Web Forms, layouts serve the same purpose as master pages, but offer a
simple syntax and greater flexibility. A basic structure of layout is given below:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>

You can use a layout to define a common template for your site. A layout can be declared at the top of
view as:

@{
Layout = "~/Views/Shared/SiteLayout.cshtml";
}

Q. What are RenderBody and RenderPage in ASP.NET MVC?


Ans. RenderBody method exists in the Layout page to render child page/view. It is just like the
ContentPlaceHolder on master page. A layout page can have only one RenderBody method.

<body>
@RenderBody()
@RenderPage("~/Views/Shared/_Header.cshtml")
@RenderPage("~/Views/Shared/_Footer.cshtml")
@RenderSection("scripts",false)
@section scripts{
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
}
</body>

RenderPage method also exists in the Layout page to render other page exists in your application. A
layout page can have multiple RenderPage method.

@RenderPage("~/Views/Shared/_Header.cshtml")

Q. What is App_Start folder in ASP.NET MVC?


Ans. App_Start folder has been introduced in MVC4. It contains various configurations files like as
BundleConfig.cs, FilterConfig.cs, RouteConfig.cs, WebApiConfig.cs for your application. All these settings
are registered within Application_Start method of Global.asax.cs file.
 BundleConfig.cs - This is used to create and register bundles for CSS and JS files. By default, various
bundles are added in these files including jQuery, jQueryUI, jQuery validation, Modernizr, and Site CSS.
 FIlterConfig.cs - This is used to register global MVC filters like error filters, actions filters etc. By default
it contains HandleErrorAttribute filter.
 RouteConfig.cs - This is used to register various route patterns for your ASP.NET MVC application. By
default, one route is registered here named as Default Route.
 WebApiConfig.cs - This is used to register various WEB API routes like as ASP.NET MVC, as well as set
any additional WEB API configuration settings.
Q. What are different ways of returning/rendering a view in ASP.NET MVC?
Ans. There are four different ways for returning/rendering a view in ASP.NET MVC as given below:

1. Return View() - This tells MVC to generate HTML to be displayed for the specified view and sends it to
the browser. This acts like as Server.Transfer() in ASP.NET WebForm.

2. Return RedirectToAction() - This tells MVC to redirect to specified action instead of rendering HTML.
In this case, browser receives the redirect notification and make a new request for the specified action.
This acts like as Response.Redirect() in ASP.NET WebForm.

Moreover, RedirectToAction construct a redirect URL to a specific action/controller in your application


and use the route table to generate the correct URL. RedirectToAction cause the browser to receive a
302 redirect within your application and gives you an easier way to work with your route table.

3. Return Redirect() - This tells MVC to redirect to specified URL instead of rendering HTML. In this case,
browser receives the redirect notification and make a new request for the specified URL. This also acts
like as Response.Redirect() in ASP.NET WebForm. In this case, you have to specify the full URL to
redirect.
Moreover, Redirect also cause the browser to receive a 302 redirect within your application, but you
have to construct the URLs yourself.
4. Return RedirectToRoute() - This tells MVC to look up the specifies route into the Route table that is
defined in global.asax and then redirect to that controller/action defined in that route. This also make a
new request like RedirectToAction().

Note:
1. Return View doesn't make a new requests, it just renders the view without changing URLs in the
browser's address bar.
2. Return RedirectToAction makes a new requests and URL in the browser's address bar is updated with
the generated URL by MVC.
3. Return Redirect also makes a new requests and URL in the browser's address bar is updated, but you
have to specify the full URL to redirect
4. Between RedirectToAction and Redirect, best practice is to use RedirectToAction for anything dealing
with your application actions/controllers. If you use Redirect and provide the URL, you'll need to modify
those URLs manually when you change the route table.
5. RedirectToRoute redirects to a specific route defined in the Route table.

Q. What are differences among ViewData, ViewBag, TempData and Session?


Ans. In ASP.NET MVC there are three ways - ViewData, ViewBag and TempData to pass data from
controller to view and in next request. Like WebForm, you can also use Session to persist data during a
user session.
ViewData
 ViewData is a dictionary object that is derived from ViewDataDictionary class.
 ViewData is used to pass data from controller to corresponding view.
 Its life lies only during the current request.
 If redirection occurs then its value becomes null.
 It’s required typecasting for getting data and check for null values to avoid error.

ViewBag
 ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
 Basically it is a wrapper around the ViewData and also used to pass data from controller to
corresponding view.
 Its life also lies only during the current request.
 If redirection occurs then its value becomes null.
 It doesn’t required typecasting for getting data.

TempData
 TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives
session.
 TempData is used to pass data from current request to subsequent request (means redirecting from
one page to another).
 Its life is very short and lies only till the target view is fully loaded.
 It’s required typecasting for getting data and check for null values to avoid error.
 It’s used to store only one time messages like error messages, validation messages.

Session
 Session is also used to pass data within the ASP.NET MVC application and Unlike TempData, it never
expires.
 Session is valid for all requests, not for a single redirect.
 It’s also required typecasting for getting data and check for null values to avoid error.

You might also like