ASP.Net MVC Interview Questions Part 3

What are the Benefits of Area in MVC?

“Benefits of Area in MVC

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

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.

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”

ASP.Net MVC Interview Questions

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, Text Box, Text Area, etc.

HTML Helper Example in MVC

@Html.ActionLink(“”Create New””, “”create””)
The above example generates an HTML link something like Create New”

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 Map Route() extension method of Route Collection. “

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

Advance ASP.Net MVC Interview Questions

How can you handle multiple Submit buttons pointing to multiple actions in a single MVC view?

“Let us elaborate on what the interviewer wants to ask because the above question is just a single liner and is not clear about what the interviewer wants.

Take a scenario where you have a view with two submit buttons as shown in the below code.

Copy Code

In the above code when the end user clicks on any of the submit buttons it will make a HTTP POST to “Action1”.

The question from the interviewer is:-

“What if we have want that on “Submit1” button click it should invoke “Action1” and on the “Submit2” button click it should invoke “Action2”.”

Now that we have understood the question let us answer the question in a detailed manner. There are two approaches to solve the above problem one is the normal HTML way and the other is the “Ajax” way.

In the HTML way we need to create two forms and place the “Submit” button inside each of the forms. And every form’s action will point to different / respective actions. You can see the below code the first form is posting to “Action1” and the second form will post to “Action2” depending on which “Submit” button is clicked.

Copy Code

In case the interviewer complains that the above approach is not AJAX this is where the second approach comes in. In the Ajax way we can create two different functions “Fun1” and “Fun1” , see the below code. These function will make Ajax calls by using JQUERY or any other framework. Each of these functions are binded with the “Submit” button’s “On Click” events.

Copy Code

How can we do exception handling in MVC?

“In the controller you can override the “On Exception” event and set the “Result” to the view name which you want to invoke when 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.

Copy Code
public class HomeController : Controller
protected override void OnException(ExceptionContext filterContext)
Exception ex = filterContext.Exception;
filterContext.ExceptionHandled = true;

 var model = new HandleErrorInfo(filterContext.Exception, ""Controller"",""Action"");

 filterContext.Result = new ViewResult()

View Name = “”Error””,
ViewData = new ViewDataDictionary(model)


To display the above error in view we can use the below code

Copy Code

What kind of logic view model class will have?

“As the name says view model this class has the gel code or connection code which connects the view and the model.

So the view model class can have following kind of logics:-

Color transformation logic: – For example you have a “Grade” property in model and you would like your UI to display “red” color for high level grade, “yellow” color for low level grade and “green” color of ok grade.
Data format transformation logic :-Your model has a property “Status” with “Married” and “Unmarried” value. In the UI you would like to display it as a checkbox which is checked if “married” and unchecked if “unmarried”.
Aggregation logic: -You have two differentCustomer and Address model classes and you have view which displays both “Customer” and “Address” data on one go.
Structure downsizing: – You have “Customer” model with “customerCode” and “CustomerName” and you want to display just “CustomerName”. So you can create a wrapper around model and expose the necessary properties.”

ASP.Net MVC Interview Questions

How do we implement minification?

When you implement bundling, minification is implemented by itself. In other words the steps to implement bundling and minification are the same.

Explain minification and how to implement it

“Minification reduces the size of script and CSS files by removing blank spaces , comments etc. For example below is a simple javascript code with comments.

Copy Code
// This is test
var x = 0;
x = x + 1;
x = x * 2;
After implementing minification the JavaScript code looks like below. You can see how whitespaces and comments are removed to minimize file size, thus increasing performance.

Copy Code
var x=0;x=x+1;x=x*2;”

How can you test bundling in debug mode?

“If you are in a debug mode you need to set EnableOptimizations to true in the bundleconfig.cs file or else you will not see the bundling effect in the page requests.

Copy Code
Bundle Table. Enable Optimizations = true;”

Advance ASP.Net MVC Interview Questions

What is bundling and minification in MVC?

Bundling and minification helps us improve request load times of a page thus increasing performance.

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.

Copy Code
public Action Result Some Action()
if (Request.HttpMethod == “”POST””)
return View(“”Some Page””);
return View(“”Some Other Page””);

Can we create our custom view engine using MVC?

“Yes, we can create our own custom view engine in MVC. To create our own custom view engine we need to follow three steps:

Let’ say we want to create a custom view engine where in the user can type a command like “” and it should display the current date and time.

Step 1: We need to create a class which implements the iView interface. In this class we should write the logic of how the view will be rendered in the render function. Below is a simple code snippet for that.

Copy Code
public class My Custom View : IView
private string _Folder Path; // Define where our views are stored
public string Folder Path
get { return _Folder Path; }
set { _Folder Path = value; }

public void Render(ViewContext viewContext, System.IO.TextWriter writer)
   // Parsing logic <dateTime>
    // read the view file
    string strFileData = File.ReadAllText(_FolderPath);
    // we need to and replace <datetime> value
    string strFinal = strFileData.Replace(""<DateTime>"", DateTime.Now.ToString());
    // this replaced data has to sent for display

Step 2: We need to create a class which inherits from Virtual Path Provider View Engine and in this class we need to provide the folder path and the extension of the view name. For instance, for Razor the extension is “cshtml”; for aspx, the view extension is “.aspx”, so in the same way for our custom view, we need to provide an extension. Below is how the code looks like. You can see the View Location Formats is set to the Views folder and the extension is “.myview”.

Shrink ▲ Copy Code
public class My View Engine Provider : Virtual Path Provider View Engine
// We will create the object of My custom view
public My View Engine Provider() // constructor
// Define the location of the View file
this. View Location Formats = new string[] { “”~/Views/{1}/{0}.myview””,
“”~/Views/Shared/{0}.my view”” }; //location and extension of our views
protected override IView Create View(
ControllerContext controllerContext, string viewPath, string masterPath)
var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath);
MyCustomView obj = new MyCustomView(); // Custom view engine class
obj.FolderPath = physicalpath; // set the path where the views will be stored
return obj; // returned this view paresing
// logic so that it can be registered in the view engine collection
protected override IView Create Partial View(Controller Context controller Context, string partial Path)
var physical path = controller Context. Http Context. Server. Map Path(partialPath);
My Custom View obj = new My Custom View(); // Custom view engine class
obj. Folder Path = physical path; // set the path where the views will be stored
return obj;
// returned this view paresing logic
// so that it can be registered in the view engine collection
Step 3: We need to register the view in the custom view collection. The best place to register the custom view engine in the ViewEngines collection is the global.asax file. Below is the code snippet for that.

Copy Code
protected void Application Start()
// Step3 :- register this object in the view engine collection
ViewEngines.Engines.Add(new MyViewEngineProvider());
} “

ASP.Net MVC Interview Questions

If we have multiple filters, what’s the sequence for execution?

“Authorization filters
Action filters
Response filters
Exception filters”

How do you implement Forms authentication in MVC?

“Forms authentication is implemented the same way as in ASP.NET. The first step is to set the authentication mode equal to Forms. The login URL points to a controller here rather than a page.

Copy Code
We also need to create a controller where we will check if the user is proper or not. If the user is proper we will set the cookie value.

Copy Code

public ActionResult Login()
if ((Request.Form[“”txtUserName””] == “”Shiv””) &&
(Request.Form[“”txtPassword””] == “”Shiv@123″”))
return View(“”About””);
return View(“”Index””);

All the other actions need to be attributed with the Authorize attribute so that any unauthorized user making a call to these controllers will be redirected to the controller (in this case the controller is “Login”) which will do the authentication.

Copy Code
Public Action Result Default()
return View();
public Action Result About()
return View();
} “

How to implement Windows authentication for MVC?

“For Windows authentication you need to modify the web.config file and set the authentication mode to Windows.

Copy Code

Then in the controller or on the action, you can use the Authorize attribute which specifies which users have access to these controllers and actions. Below is the code snippet for that. Now only the users specified in the controller and action can access it.

Copy Code
[Authorize(Users= @””WIN-3LI600MWLQN\Administrator””)]
public class StartController : Controller
// GET: /Start/
[Authorize(Users = @””WIN-3LI600MWLQN\Administrator””)]
public ActionResult Index()
return View(“”My View””);
} “

Advance ASP.Net MVC Interview Questions

How can you do authentication and authorization in MVC?

You can use Windows or Forms authentication for MVC.

So which is a better fit, Razor or ASPX?

As per Microsoft, Razor is more preferred because it’s light weight and has simple syntaxes.

Why Razor when we already have ASPX?

“Razor is clean, lightweight, and syntaxes are easy as compared to ASPX. For example, in ASPX to display simple time, we need to write:

Copy Code
In Razor, it’s just one line of code:

Copy Code

ASP.Net MVC Interview Questions

What is Razor in MVC?

It’s a light weight view engine. Till MVC we had only one view type, i.e., ASPX. Razor was introduced in MVC 3.

Can we display all errors in one go?

Yes, we can; use the ValidationSummary method from the Html helper class.

Copy Code
<%= Html.ValidationSummary() %>
What are the other data annotation attributes for validation in MVC?

If you want to check string length, you can use StringLength.

Copy Code
public string FirstName { get; set; }
In case you want to use a regular expression, you can use the RegularExpression attribute.

Copy Code
[RegularExpression(@””[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}””)]public string Email { get; set; }
If you want to check whether the numbers are in range, you can use the Range attribute.

Copy Code
[Range(10,25)]public int Age { get; set; }
Sometimes you would like to compare the value of one field with another field, we can use the Compare attribute.

Copy Code
public string Password { get; set; }[Compare(“”Password””)]public string ConfirmPass { get; set; }
In case you want to get a particular error message , you can use the Errors collection.

Copy Code
var ErrMessage = ModelState[“”Email””].Errors[0].ErrorMessage;
If you have created the model object yourself you can explicitly call TryUpdateModel in your controller to check if the object is valid or not.

Copy Code
In case you want add errors in the controller you can use the AddModelError function.

Copy Code
ModelState.AddModelError(“”FirstName””, “”This is my server-side error.””);”

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.

Copy Code
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.

Copy Code
string str = TempData.Peek(“”Td””).ToString();”

Advance ASP.Net MVC Interview Questions

What is difference between TempData and ViewData ?

“TempData” maintains data for the complete request while “ViewData” maintains data only from Controller to the view.

How can we restrict MVC actions to be invoked only by GET or POST?

“We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the DisplayCustomer action can only be invoked by HttpGet. If we try to make HTTP POST on DisplayCustomer, it will throw an error.

Copy Code
public ViewResult DisplayCustomer(int id)
Customer objCustomer = Customers[id];
return View(“”DisplayCustomer””,objCustomer);
} “

How can we maintain sessions in MVC?

Sessions can be maintained in MVC by three ways: tempdata, viewdata, and viewbag.

ASP.Net MVC Interview Questions

“By using the Action Link method as shown in the below code. The below code will create a simple URL which helps to navigate to the “Home” controller and invoke the Go to Home action.

Copy Code
<%= Html.ActionLink(“”Home””,””Gotohome””) %> “

What is the advantage of defining route structures in the code?

“Most of the time developers code in the action methods. Developers can see the URL structure right upfront rather than going to the “routeconfig.cs” and see the lengthy codes. For instance in the below code the developer can see right upfront that the “GotoAbout” action can be invoked by four different URL structure.

Can we map multiple URL’s to the same action?

Yes, you can, you just need to make two entries with different key names and specify the same controller and action.

Advance ASP.Net MVC Interview Questions

Where is the route mapping code written?

The route mapping code is written in “RouteConfig.cs” file and registered using “global.asax” application start event.

What is routing in MVC?

“Routing helps you to define a URL structure and map the URL with the controller.

For instance let’s say we want that when a user types “http://localhost/View/ViewCustomer/”, it goes to the “Customer” Controller and invokes the Display Customer action. This is defined by adding an entry in to the routes collection using the maproute function. Below is the underlined code which shows how the URL structure and mapping with controller and action is defined.

Copy Code
“”View””, // Route name
“”View/ViewCustomer/{id}””, // URL with parameters
new { controller = “”Customer””, action = “”DisplayCustomer””,
id = UrlParameter.Optional }); // Parameter defaults “

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

“Both of them provide the same HTML output, “HTML. Text Box For” is strongly typed while “HTML. Textbox” isn’t. Below is a simple HTML code which just creates a simple textbox with “Customer Code” as name.

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

Copy Code
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”.”

ASP.Net MVC Interview Questions

What is the difference between each version of MVC 2, 3 , 4, 5 and 6?


ASP.NET MVC and Web API has been merged in to one.

Dependency injection is inbuilt and part of MVC.

Side by side – deploy the runtime and framework with your application

Everything packaged with NuGet, Including the .NET runtime itself.

New JSON based project structure.

No need to recompile for every change. Just hit save and refresh the browser.

Compilation done with the new Roslyn real-time compiler.

vNext is Open Source via the .NET Foundation and is taking public contributions.

vNext (and Rosyln) also runs on Mono, on both Mac and Linux today.



Attribute based routing

Asp.Net Identity

Bootstrap in the MVC template

Authentication Filters

Filter overrides



Refreshed and modernized default project templates

New mobile project template

Many new features to support mobile apps

Enhanced support for asynchronous methods



Readymade project templates

HTML 5 enabled templates

Support for Multiple View Engines

JavaScript and Ajax

Model Validation Improvements


Client-Side Validation

Templated Helpers


Asynchronous Controllers

Html.ValidationSummary Helper Method

DefaultValueAttribute in Action-Method Parameters

Binding Binary Data with Model Binders

DataAnnotations Attributes

Model-Validator Providers

New RequireHttpsAttribute Action Filter

Templated Helpers

Display Model-Level Errors”

What is the latest version of MVC?

MVC 6 is the latest version which is also termed as ASP VNEXT.

Is MVC suitable for both Windows and Web applications?

The MVC architecture is suited for a web application than Windows. For Window applications, MVP, i.e., “Model View Presenter” is more applicable. If you are using WPF and Silverlight, MVVM is more suitable due to bindings.

Advance ASP.Net MVC Interview Questions

What is Attribute Routing?

“MVC routing uses the route table to look up and call the desired controller method, which renders the respected view. We can provide the routes in routeconfig file.

Sometimes it is required to have routes that are different from the ones configured in routeconfig and is specific to any controller or controller action method. In this attribute, routing comes into the picture.

To enable attribute based routing to add below line to routeconfig file under RegisterRoutes methods.


Samples of attribute routing:

This route is to get a product with a given id. If id not provided then return all products

[Route Prefix(“products”)]
This is places over the controller. All routes that start with products come to here

[Route Area(“business”)]
Route Area is a way to specify are in the route. It is just to let the route know that controller belongs to some area.”

What is Area in MVC

“MVC have separate folders for Model, View and Controller. In the case of large projects, it becomes unmanageable with the default MVC structure. MVC 2 has introduced Area.
The area allows partitioning of large applications into smaller units, where each unit contains a separate folder structure, which is as the default MVC structure.
For Example, Large applications may have different modules like admin, HR etc. So Area can contain separate MVC folder structure for each module.

Create MVC Area

To add MVC Area into your application, follow the below steps:

Right-click to project solution explorer -> Add -> Area
Enter the name of the area in the dialogue box and click Add button
An area with a given name gets added with separate MVC folder structure.”

What is “Unobtrusive Validation?

“Unobtrusive JavaScript library allows to add validation to MVC views without any additional coding, only required to use attributes like Required Attribute, Range Attribute and include the correct script files.


public class Add User VM
[Display Name(“”First Name:””)]
[Required(Error Message = “”Please enter the first name.””)]
public string FirstName { get; set; }
[Display Name(“”Last Name:””)]
[Required(Error Message = “”Please enter the last name.””)]
public string Last Name { get; set; }
[Display Name(“”Age:””)]
[Range(12, 120, Error Message = “”You must be between 12 and 120 years of age.””)]
public int Age { get; set; }
[Display Name(“”Email:””)]
[Required(Error Message = “”Please enter an email address.””)]
[Email Address(Error Message = “”Please enter a valid email address.””)]
public string Email Address { get; set; }
The above class setup is to handle the server side validations. Unobtrusive validations allow us to take existing validation attributes and use them at client-side to make the user experience much better.”

ASP.Net MVC Interview Questions

Explain Scaffolding in MVC

“ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Scaffolding quickly adds code that interacts with data models and reduces the amount of time to develop standard data operations in the project. With the help of scaffolding, we can add views of Index, Create, Edit actions very easily and the code is itself added for each view and action methods.

Scaffolding consists of Scaffold templates like page templates, entity page templates, field page templates, and filter templates. These templates allow to quickly build a functional data-driven Website. They are used to generate code for basic CRUD operations against the database with the help Entity Framework. These templates the Visual Studio T4 templating system to generate views for basic CRUD operations with the help of Entity Framework”

What are the options that 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 the confirm box.
On Begin: method name to be given here and this will be called before the AJAX request.
On Complete: method name to be given here and this will be called at the end of AJAX request.
On Success: method name to be given here and this will be called when AJAX request is successful.
On Failure: method name to be given here and this will be called when AJAX request is failed.
Update Target Id: Target element which is populated from the action returning HTML.”

Explain Render Section in MVC?

“Render Section is used to designate a place to render content that is different from the one in RenderBody.


@RenderSection(“”footer””, required: false)

By default, a section is required. We pass required: false to designate that section is optional.

@Section is used to render section in View as:

@section Footer


Section/Index page

Advance ASP.Net MVC Interview Questions

What is the flow of the Request in MVC application?

“When the request is made by any client then at first it goes to the URL Routing, where the URL is compared to the routes that are present in the routing table. This helps to identify the controller and action method name.

Based on the identified controller action method is called by passing the required parameters (if any).

From where Model is called that interacts with Database to get the required response and returns to the controller action method.

The action method parses the response in the requested Action result format and returns back to View to present to the client.

What Is Action Name? Have you ever implemented it?

“Yes, I have implemented it. Action Name is an attribute used to change the action name. Here’s how it is used in code:
public Action Result Test()
Return View();

Frequently asked MVC interview questions that you shouldn’t miss

● What do you mean by MVC Output Caching?
● Explain HTML Helpers?
● How can you manage the Action Method’s unhandled exceptions?
● Explain View Engine?
● Explain Model Binding?
● What do you mean by Temp Data, View Bag, and View Data?
● Explain request flow in MVC application?
● Explain MVC Scaffolding?
● What is JSON binding?
● What is Bundle. Config?
● Explain MVC Layout and Sections?
● Explain MVC Render Page and Render Body?
● Explain Helper Page. Is Ajax property?”

Have you ever implemented MVC? What do you think it is more suitable for; Web or Windows Application?

Yes, I have implemented MVC practically. According to my knowledge, MVC is a suitable architecture while developing web applications due to separation of concerns. We can use MVP (Model View Presenter) architecture for Windows application.

ASP.Net MVC Interview Questions

What is the method for enabling Attribute Routing?

To enable attribute routing, simply add Map MVC Attribute Routes() method to the code. MVC Part MVC Part 2
Back to top