Following are some of the MVC Interview Questions and Answers for Experienced.
These questions are commonly asked in interviews and will also help you to get better understanding of the framework.These are some of the MVC Interview Questions and answers for experienced people.They cover some of the most important topics in MVC.
To answer questions in any interview you should have understanding of basic concepts.If you have knowledge of basics then you will find it easier to answer questions related to more advanced scenarios.
These mvc interview questions are segregated into different groups,so you can go through them when you are trying to brush up the main concepts in MVC.
Basic Questions asked in mvc interviews
1)What is ASP.NET MVC?
ASP.NET MVC is a web development framework used for creating web applications on the ASP.NET platform.It is an alternative to web forms which is also based on ASP.NET for creating web applications.It is based on the Model View Controller architectural pattern which is used for creating loosely coupled applications.The three main components in MVC application are :
- Model represents the business entities.These are identified from the requirement.
- View used to render the UI
- Controller receives the end user request,performs operations on the model as required and renders the view.
2)What are the advantages of MVC?
a)Separation of Concerns-SoC
MVC encourages developers to implement the application using separation of concerns.This means that you can easily update either of the three components : model , view or controller without impacting the other components.
For example view can be changed without the need to change model or controller.Similarly Controller or Business Logic in your Model class can be updated easily without impacting the rest of the MVC application.
b)Easy to Unit test
Since the components are independent so you can easily test the different components in isolation.This also facilitates automated test cases.
c)Full Control over the generated HTML
MVC views contains HTML so you have full control over the view that will be rendered.Unlike WebForms no server controller are used which generates unwanted HTML.
3)What are the main differences between ASP.NET WebForms and ASP.NET MVC?
WebForms | MVC |
There is no proper separation of concerns,the application logic resides in the code behind the Webform ,so the .aspx page and its code behind are tightly coupled.This makes it difficult to make the changes in one without effecting the other. | In the case of ASP.NET MVC there is a separation of concerns ,so the Model,View and Controller are loosely coupled.This means that we can easily make changes in one component without effecting the other components. |
There is viewstate | There is no Viewstate.As viewstate needs to be transferred in every request so it increases the size of the page. |
Limited control over the generated HTML | MVC provides you complete control over the generated HTML as you don’t use server side controls. |
4)Is there ViewState in MVC?
This is a very commonly asked question.It lets the interviewer judge your understanding of MVC. One big difference between WebForms and MVC is MVC does not have viewstate.The reason that MVC does not have viewstate is because viewstate is stored in a hidden field on the page.So this increases the size of the page significantly and impacts the page load time.
5)What is Routing in MVC?
In WebForms the URL’s are mapped to the physical files on the file system.But in the case of ASP.NET MVC URL’s are not mapped to the physical files but are mapped to the controllers and action methods.This mapping is done by the routing engine.To map the URL to the controllers and action methods ,the routing engine defines the routes.Based on the matching route the request is handled by the appropriate controller.
We can depict the role of the routing engine with the following diagram:
Routes are declared in RouteConfig class which is in the App_Start folder.Route consists of Route Name and URL Pattern.If the incoming request matches the route then it is handled by the specified action method and controller.
Suppose you request for the URL http://samplesite/home/index and you have declared the route as below.This request will be handled by the Home controller’s Index method
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}"
);
6)What are Action Methods?
Action methods are defined by the controllers ,urls are mapped to the action methods.
The request which is received by our mvc application is ultimately handled by an action method.Action method generates the response in the form of ActionResult.The action method to execute is determined according to the routing rules defined by our application.
7)What is ActionResult?
ActionResult is a class which helps in creating decoupled application.Instead of returning specific type of result action method return an object of type ActionResult.
ActionResult is a class which represents the result of an action method.Action methods returns an object of a type which derives from this ActionResult class.Since ActionResult is an abstract class so it provides few derived classes whose object the action method can return as the response.Also there are few methods available in the controller base class for creating objects of ActionResult derived classes,so we don’t need to explicitly create an object of the ActionResult and can just call the method.
Some of the classes deriving from the ActionResult are:
Action Result | Helper Method | Description |
ViewResult | View | Renders a view |
PartialViewResult | PartialView | Renders a partial view, which is a view which can be used inside another view. |
RedirectResult | Redirect | Redirects to different action method as specified in the URL. |
RedirectToRouteResult | RedirectToRoute | Redirects to another action method. |
ContentResult | Content | Returns the user supplied content type. |
JsonResult | Json | Returns a JSON object. |
The same action method can return different action results based on the scenario
8)What are HTML helpers?
HTML helpers are methods which returns HTML strings.There are few inbuilt HTML helpers which we can use.If the inbuilt helpers are not meeting our needs ,we can also create our custom HTML helpers.They are similar to the webforms controls as both the webforms controls and the MVC HTML helpers returns HTML.
But HTML helpers are lightweight compared to the webforms controls.
Following are some of the commonly used HTML helper methods for rendering the HTML form elements
- BeginForm()
- EndForm()
- TextArea()
- TextBox()
- CheckBox()
- RadioButton()
- DropDownList()
- Hidden()
- Password()
This question is almost always asked in MVC interview:
9) Can you overload action methods?
You can overload action methods by passing the method name in the ActionName attribute as:
[ActionName("MyActionMethod")]
public ActionResult GetDetails(int id)
{
return "";
}
now you can declare another action method with the same name as:
public ActionResult GetDetails() { return ""; }
10)What are Filters?
Sometimes we want to execute some logic either before the execution of the action method or after the execution of the action method.We can use Action Filter for such kind of scenario.Filters defines 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:
- Authorization filter (implements IAuthorizationFilter)
- Action filter (implements IActionFilter)
- Result filter (implements IResultFilter)
- Exception filter (implementsIExceptionFilter attribute)
Filters are executed in the above order when multiple filters are attached to an action method.
For example to apply authorization filter we apply the attribute as:
[Authorize]
public ActionResult Index()
{
return View();
}
11)Which Filter executes last?
Exception filter executes last,after all the other filters have executed.
12)How do you implement authorization in MVC application?
Authorize attribute is used to control access to controller and action methods.For example we can restrict access to Details method to only authenticated users:
public class HomeController : Controller
{
public ActionResult Index()
{
}
[Authorize]
public ActionResult Details()
{
}
}
It has different parameters using which you can control who can access the controller or action method.For example you can declare that only Administrator users are able to access your Controller methods
[Authorize(Roles = "Administrator")]
public class AdministrationController : Controller
{
}
13)Explain about Razor view engine?
View engine allows us to use server side code in web pages.This server side code is compiled on the server itself before getting sent to the browser.
Razor and Web forms are the default view engines in MVC. Razor view have the extension cshtml for view containing c# code and vbhtml for views containing vb.net code.
Razor has the following features:
- Razor view define code blocks which starts with { and ends with }.Single or multiple statements can be defined in the code block
- Code block starts with @
- Inline expressions can be mixed with normal html and are not required to start with @.
Single line statement
@{ var var name="Marc";}
multiline statement
@{ var name="Marc"; var a=1; }
14)How to return JSON response from Action method?
To return JSON response Action method needs to return the JsonResult object.To return the JsonResult object call the Json helper method.Following action method called SampleMsg returns a response in JSON format
public JsonResult SampleMsg()
{
string msg = "hello";
return Json(msg, JsonRequestBehavior.AllowGet);
}
15)What is a Partial View?
Partial View is a view that can be used in other views.This helps reuse the existing functionality in other views.An example of this are menu items.Since these items are common across all the different views so we may end up duplicating the same html across many different views.A better approach is to design a partial view which can be reused in many different views.
16)How do you generate hyperlink?
Using the Html.ActionLink helper method hyperlink is inserted in view.If you pass the action method name and controller name to ActionLink method then it returns the hyperlink.For example to generate hyperlink corresponding to the controller called Organization and action method called Employees you can use it as:
@Html.ActionLink("this is hyperlink", "Organization", "Employees")
17)What is OutputCaching in MVC?
OutputCaching allows you to store the response of the action method for a specific duration.This helps in performance as the saved response is returned from the action method instead of creating a new response. Following action method will return the saved response for next 30 seconds.
OutputCache(Duration = 30)] public string SayHello() { return "Hello"; }
OutputCache attribute can be applied either to individual action methods or to the entire controller.If you apply it to the action method then the response of only that action method is cached.
18)How do you manage unhandled exceptions in Action method?
The HandleError Error attribute is used for managing unhandled exceptions in action method.In the absence of the HandleError attribute if an unhandled exception is thrown by an action method then the default error page is shown which displays sensitive application information to everybody.
Before using HandleError you need to enable custom errors in the web.config file:
<system.web> <customErrors mode="On" defaultRedirect="Error" /> </system.web>
HandleError has few properties which can be used for handling the exception:
- ExceptionType
- View
- Master
- Order
19)What is a View Engine?
View Engines are responsible for generating the HTML from the views.Views contains HTML and source code in some programming language such as C#. View Engine generates HTML from the view which is returned to the browser and rendered.Two main View Engines are WebForms and Razor ,each has its own syntax.
20)What is Area?
A large MVC application can consist of lots of controller, view and models. This makes the application difficult to manage. To manage the complexity of large MVC application you group the application in different areas based on the functionality.
You create different areas for different functionalities. Each Area consists of controllers, views and models related to the functionality. For example an eCommerce application can consist of modules related to user registration, product management and billing. You can group these functionalities into corresponding areas. You create areas and use the same folder structure in Areas which you use to create a normal MVC application. Each Area has a different folder.
21)What is Model Binding?
In your action methods you need to retrieve data from the request and use that data.Model binding in MVC maps the data from the HTTP Request to the action method parameters.The repetitive task of retrieving data from the HTTPRequest is removed from the action method.This allows the code in the action method to focus only on the logic.
22)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 defined as:
- Required
- DataType
- Range
- StringLength
For example to implement validation for the Name property declared in a class use:
[Required(ErrorMessage="Name is required")] public string Name { set; get; }
you can use html helper for the above property in view as:
Html.TextBoxFor(m => m.Name)
23)What are ViewData, ViewBag and TempData ?
ViewData, ViewBag and TempData are used for passing data from the controller to the view. ViewBag and ViewData are used to pass the data from the controller to the view while TempData can also pass the data from one controller to another controller or one action method to another action method.TempData uses session internally.
ViewData is a dictionary of objects which are set in the action method and accessed in the View.ViewBag is a dynamic type,so it can define any property which could then be accessed from the view.Dynamic type is part of C# since C# 4.0 .
This question is commonly asked if you have some work experience,more than 3 years, in developing MVC applications.
Commonly asked mvc interview questions if you have 2+ years of experience
24)What is the flow of the Request in MVC application?
At a high level we can depict the flow of the request with the following diagram:
This is just a high level overview of how a request is handled by MVC application.To summarize following happens to handle a request:
- UrlRoutingModule searches the routes defined in the routes table.
- When a matching pattern for the requested URL is found ,corresponding controller and action method are determined.
- An object of controller class is created
- Execute() method of the controller class is invoked.
- Controller queries or updates the model and returns the view.
25)Where are the routes for the application defined?
When the application starts ,the RegisterRoutes method is called from the application_start method of glabal.asax.In the RegisterRoutes method routes are added to the route table using the MapRoute method.
The RouteConfig.cs contains the RegisterRoutes method which is defined as
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{name}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }
The above method is called from the Application_Start method of the Global.asax as:
26)Which assembly contains the ASP.NET MVC classes and interfaces?
The main functionality of ASP.NET MVC is defined in the System.Web.Mvc assembly.It contains the classes and interfaces which supports the MVC functionality. System.Web.Mvc is the namespace which contains the classes used by the MVC application.
27)What are strongly typed Helpers?
In the case of normal helper methods we need to provide the string values to the helper methods.As these are string literals so there is no compile time checking and also intellisense support is available.
In contrast strongly typed helper methods takes lambda expressions so they provide
intellisense support and also are type checked at compile time.
Following are the normal and strongly typed helper methods which generates the same HTML
Html.TextBox("Name") Html.TextBoxFor(model => model.Name)
28)What is _ViewStart.cshtml?
_ViewStart.cshtml defines code which is executed before any code in any of the views is executed.It is applied to all the views in a subdirectory.For example following is commonly included in _ViewStart.cshtml file:
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
The above razor block will set a common layout for all the views.We can include our own code also in _Layout.cshtml which we want to execute before the code in any of the view executes.
For defining the UI elements which are common for multiple views in your application you use _layout.cshtml.It is added to the shared folder in the views directory as it is shared by multiple views.
29)What is MVC Scaffolding?
It is a code generation framework for ASP.NET applications There are p reinstalled code generators for MVC and Web API projects in Visual Studio.It allows to quickly add common code such as code which interacts with data models.
30)What are the new features of MVC 5?
Some of the features included in MVC5 are
- Scaffolding
- ASP.NET Identity
- One ASP.NET
- Bootstrap
- Attribute Routing
- Filter Overrides
31)What is Bundling and Minification?
Bundling and Minification is used for improving the performance of the application.When external JavaScript and CSS files are referenced in a web page then separate HTTP Requests are made to the server to fetch the contents of those files.So for example if your page references files called Common.js and Common.cs in a web page as:
<script type="text/javascript" src="../Scripts/Common.js"/>
<link rel="stylesheet" type="text/css" href="../CSS/Common.css">
then your web page will make two separate HTTP requests to fetch the contents of Common.js and Common.cs.This results is some performance overhead.Bundling and Minification is used to overcome this performance overhead.
Bundling reduces the number of HTTP requests made to the server by combining several files into a single bundle.Minification reduces the size of the individual files by removing unnecessary characters.
You can enable Bundling by setting a property called EnableOptimizations in “BundleConfig.cs” in App_Start folder.
32)What is attribute routing in MVC?
MVC 5 has introduced an attribute called “route”.Using this attribute we can define the URL structure at the same place where action method is declared.This allows the action method to be invoked using the route defined in the route attribute.For example following action method can be invoked using the url pattern “Items/help”
[Route("Items/help")] public ItemsHelp() { return View(); }
33)What are Ajax helper methods?
Ajax helper methods are like HTML helper methods.The difference between the two is that HTML helper methods sends request to action methods synchronously while AJAX helper methods calls action methods asynchronously.You need to include the following nuget in your project for working with ajax helper methods:
Microsoft.jQuery.Unobtrusive.Ajax
To generate action link using ajax helper method you can use the following code:-
@AJAX.ActionLink((“Link Text”, “Action Method”, new AjaxOptions {UpdateTargetId = “id”, HttpMethod = “GET” })
For detailed information about Ajax Helper methods refer Ajax Helpers in ASP.NET MVC
34)What is glimpse?
Glimpse are NuGet packages which helps in finding performance, debugging and diagnostic information.Glimpse can
help you get information about timelines,model binding,routes,environment etc.
35)How can we prevent Cross Site Request Forgery(CSRF)?
To prevent CSRF we apply the ValidateAntiForgeryToken attribute to an action method:
[ValidateAntiForgeryToken()]
36)What is MVC 6?
In MVC 6 ,the three frameworks,WebAPI ,MVC and SingnalR are merged into a single framework.Also in MVC dependency on System.Web is removed.It provides features such as:
- Application is automatically compiled
- Can be run other hosts then IIS
- json based configuration system based on the application environment
37)What is ASP.NET Core?
ASP.NET Core is a new version of ASP.NET.It is more than just another version of ASP.NET .ASP.NET Core is a web framework for developing modern web applications and cloud applications.It has number of useful features such as:
- Cross platform supports all the major OS such as Linux,Windows,Mac.
- Open source ASP.NET Core has huge community of developers who contribute to add new features frequently
- Modular and Lightweight Unlike ASP.NET which was based on System.Web.dll,ASP.Core is consumed using Nuget packages.You only need to add the nuget packages you require for a specific functionality.
- Integrated ASP.NET Core could be used for developing both UI based web applications and WebAPIs
These are some of the most important MVC interview questions and answers which you should know when attending MVC interview.These questions will not only help you with the interview but would also help in understanding MVC. better.
For C# interview questions and answers,refer C# interview questions