MVC Interview Questions and Answers

In this article I would like to explain about most frequently asked ASP.NET MVC Interview Questions. This collection is useful for both freshers and experienced candidates to clear technical ASP.NET MVC interviews.

1. What is MVC?

If you go for an MVC interveriew then most of the questions will be circulated on Models, Views and Controllers. So if you clearly understand the difference among these three then you can easily crack most of the MVC Interview Questions.

MVC is an architectural pattern which separates the representation and the user interaction. It’s divided into three broader sections, Model, View and Controller. Below is how each one of them handles the task.

MVC Interview Questions - Model View Controller

Model
A Model is data used by a program. This may be a database, file, or a simple object which provides data to the View to display.

View
View is a user interface. View displays data from the Model to the user and also enables them to modify the data.

Controller
The Controller is responsible to take the end user request and load the appropriate Model and View.

2. Explain about ASP.MVC Page Life Cycle

This is one of the most commonly asked Interview Question from the list of ASP.NET MVC Interview Questions.

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.

For more information please refer one of my other article on ASP.NET MVC Page Life Cycle.

3. How Model, View and Controller communicate with each other in ASP.NET MVC?

There are following rules for communication among Model, View and Controller:

  • User interacts with the Controller.
  • There is one-to-many relationship between Controller and View means one controller can mapped to multiple views.
  • Controller and View can have a reference to model.
  • Controller and View can talk to each other.
  • Model and View cannot talk to each other directly. They communicate to each other with the help of controller.

4. What are advantages of ASP.NET MVC?

Below are the 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.

Separation of concerns is achieved as we are moving the code behind to a separate class file. By moving the binding code to a separate class file we can reuse the code to a great extent.

TDD – The MVC framework brings better support to test-driven development.

Automated UI testing is possible because now the behind code (UI interaction code) has moved to a simple .NET class. This gives us opportunity to write unit tests and automate manual testing.

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 behaviour – 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.

Support of ASP.NET features – 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.

5. What is the difference among each version of MVC?

ASP.NET MVC 1

  • Released on Mar 13, 2009
  • Runs on .NET 3.5 and with Visual Studio 2008 & Visual Studio 2008 SP1
  • MVC Pattern architecture with WebForm Engine
  • Html Helpers
  • Ajax helpers
  • Routing
  • Unit Testing

ASP.NET MVC 2

  • Released on Mar 10, 2010
  • Runs on .NET 3.5, 4.0 and with Visual Studio 2008 & 2010
  • Strongly typed HTML helpers means lambda expression based Html Helpers
  • Templated Helpers
  • UI helpers with automatic scaffolding & customizable templates
  • Support for DataAnnotations Attributes to apply model validation on both client and server sides
  • Overriding the HTTP Method Verb including GET, PUT, POST, and DELETE
  • Areas for partitioning a large applications into modules
  • Asynchronous controllers
  • Client-Side Validation
  • Binding Binary Data with Model Binders
  • Model-Validator Providers
  • Display Model-Level Errors

ASP.NET MVC 3

  • Released on Jan 13, 2011
  • Runs on .NET 4.0 and with Visual Studio 2010
  • The Razor view engine
  • Readymade project templates
  • HTML 5 enabled templates
  • Support for Multiple View Engines
  • Enhanced Data Annotations attributes for model validation on both client and server sides
  • Remote Validation
  • Compare Attribute
  • Session less Controller
  • Child Action Output Caching
  • Dependency Resolver
  • Entity Framework Code First support
  • Partial-page output caching
  • ViewBag dynamic property for passing data from controller to view
  • Global Action Filters
  • Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding
  • Use of NuGet to deliver software and manage dependencies throughout the platform
  • Model Validation Improvements

ASP.NET MVC 4

  • Released on Aug 15, 2012
  • Runs on .NET 4.0, 4.5 and with Visual Studio 2010SP1 & Visual Studio 2012
  • ASP.NET Web API
  • Refreshed and modernized default project templates
  • Mobile project template using jQuery Mobile
  • Many new features to support mobile apps
  • Display Modes
  • Task support for Asynchronous Controllers
  • Enhanced support for asynchronous methods
  • Bundling and minification
  • Support for the Windows Azure SDK

ASP.NET MVC 5

  • Released on 17 October 2013
  • Runs on .NET 4.5, 4.5.1 and with Visual Studio 2012 & Visual Studio 2013
  • One ASP.NET
  • Attribute based routing
  • ASP.NET Identity
  • ASP.NET Scaffolding
  • Authentication filters – run prior to authorization filters in the ASP.NET MVC pipeline
  • Filter overrides
  • Bootstrap in the MVC template
  • ASP.NET WEB API2
  • New Scaffolding system

6. What is Routing in ASP.NET MVC?

Routing is a pattern matching system that monitor 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.

ASP.NET MVC Routing

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.

7. What is the difference among Viewdata, Viewbag and Tempdata?

ViewData ViewBag TempData

Both ViewData and ViewBag are used to pass data from a controller to a view. ViewData is a dictionary of objects that are stored and retrieved using strings as keys. The syntax of ViewData is very similar to that of ViewState, SessionState and ApplicationState.

// Storing data in ViewData
ViewData["YourData"] = "SomeData";
// Retrieving data from ViewData
string strData = ViewData["YourData"].ToString();

ViewData does not provide compile time error checking. For example, if you mis-spell the key names you wouldn’t get any compile time error. You get to know about the error only at runtime.

ViewBag uses the dynamic feature that was introduced in to C# 4.0. It allows an object to have properties dynamically added to it. Using ViewBag the above code can be rewritten as below.

// Storing data in ViewBag
ViewBag.YourData = "SomeData";
// Retrieving data from ViewBag
string strData = ViewBag.YourData;

Just like ViewData, ViewBag does not provide compile time error checking. For example, if you mis-spell the property name, you wouldn’t get any compile time error. You get to know about the error only at runtime.

Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary.

TempData helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “tempdata” helps to maintain data between those redirects. It internally uses session variables.

8. What is life of TempData?

“TempData” is available for the current request and in the subsequent request it’s available depending on whether “TempData” is read or not.

So if “TempData” is once read it will not be available in the subsequent request.

9. 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.

@TempData["MyData"];
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.

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

Please Note: To pass data from controller to a view, It’s always a good practice to use strongly typed view models instead of using ViewBag & ViewData. Strongly typed view models provide compile time error checking.

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

In MVC we have lots of HTML helper controls to render Views. If you go for an MVC interview then it would be better to know about HTML Helpers as you may face MVC Interview Questions on HTML Helpers.

HTML helpers help you to render HTML controls in the view. For instance if you want to display a HTML textbox on the view, below is the HTML helper code.

<%= Html.TextBox("LastName") %>

For checkbox below is the HTML helper code. In this way we have HTML helper methods for every HTML control that exists.

<%= Html.CheckBox("Married") %>

11. What is the difference between “HTML.TextBox” vs “HTML.TextBoxFor”?

Both of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t.

Below is a simple HTML code which just creates a simple textbox with “CustomerCode” as name.

Html.TextBox("CustomerCode")

Below is “Html.TextBoxFor” code which creates HTML textbox using the property name “CustomerCode” from object “m”.

Html.TextBoxFor(m => m.CustomerCode)

In the same way we have for other HTML controls like for checkbox we have “Html.CheckBox” and “Html.CheckBoxFor”.

12. What are Partial Views in MVC?

If you are an asp.net web-forms developer, then you will realize that partial views in mvc are similar to user controls in asp.net webforms.

Partial views are used to encapsulate re-usable view logic and are a great means to simplify the complexity of views. These can then be used on multiple views, where we need similar view logic.

If you are using web forms view engine, then the partial views have the extension of .ascx. If the view engine is razor and programming language is c#, then partial views have the extension of .cshtml. On the other hand if the programming language is visual basic, then the extension is .vbhtml.

13. What is the difference between html.partial and html.renderpartial?

Both of these helper methods are used for rendering partial views.

Difference between html.partial and html.renderpartial

  • The return type of “RenderPartial” is void, where as “Partial” returns “MvcHtmlString”
  • Syntax for invoking Partial() and RenderPartial() methods in Razor views
@Html.Partial("PartialViewName")
{ Html.RenderPartial("PartialViewName"); }
  • Syntax for invoking Partial() and RenderPartial() methods in webform views
<%: Html.Partial("PartialViewName") %>
<% Html.RenderPartial("PartialViewName"); %> 

14. When would you use Partial() over RenderPartial() and vice versa?

The main difference is that “RenderPartial()” returns void and the output will be written directly to the output stream, where as the “Partial()” method returns MvcHtmlString, which can be assigned to a variable and manipulate it if required. So, when there is a need to assign the output to a variable for manipulating it, then use Partial(), else useRenderPartial().

Which one is better for performance?

From a performance perspective, rendering directly to the output stream is better.RenderPartial() does exactly the same thing and is better for performance over Partial().

15. What are Areas in ASP.NET MVC?

When you create a new ASP.NET MVC application, the following folders are created with in the root directory.

  1. Models
  2. Views
  3. Controllers

This structure is fine for simple applications, but when your application gets big and complex, maintaining your Models, Views and Controllers can get complicated.

The structure of a complex ASP.NET MVC application can be very easily maintained using areas. So, in short areas are introduced in ASP.NET MVC 2, that allow us to breakdown a large complex application into a several small sections called areas. These areas can have their own set of

  1. Models
  2. Views
  3. Controllers
  4. Routes

16. What are different types of ActionResults in ASP.NET MVC?

MVC ActionResult
MVC ActionResult SubTypes

17. What are different types of Filters in ASP.NET MVC?

This is also one of the most commonly asked Interview Question from the list of ASP.NET MVC Interview Questions.

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. Filters are attributes which we can apply to the action methods.

For more information please refer one of my other article on ASP.NET MVC Filters.

18. What is Bundling and Minification in ASP.NET MVC?

ASP.NET MVC4 and .NET Framework 4.5 offer bundling and minification techniques that reduce the number of request to the server and size of requested CSS and JavaScript, which improve page loading time.

A bundle is a logical group of files that is loaded with a single HTTP request. You can create style and script bundle for CSS and Java Scripts respectively by calling BundleCollection class Add() method. All bundles are create with in BundleConfig.cs file.

public class BundleConfig 
{ 
    public static void RegisterBundles(BundleCollection bundles) 
    { 
      bundles.Add(new 
      StyleBundle("~/Content/css").Include("~/Content/site.min.css", 
      "~/Content/mystyle.min.css")); 
      bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( 
      "~/Scripts/jquery-1.7.1.min.js", "~/Scripts/jquery.validate.min.js", 
      "~/Scripts/jquery.validate.unobtrusive.min.js")); 
     } 
}

Minification is technique for removing unnecessary characters (like white space, newline, tab) and comments from the JavaScript and CSS files to reduce the size which cause improved load times of a webpage.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *