ASP.NET MVC (Model View Controller) – DOT NET Chapter Wise Interview Questions

ASP.NET MVC (Model View Controller) – DOT NET Chapter Wise Interview Questions

Question 1:
What is MVC?
MVC is an architectural pattern which separates the representation and the user interaction. It’s divided in to three broader sections,“Model”, “View” and “Controller”. Figure 6.1 shows is how each one of them handles the task.

  • The “View” is responsible for look and feel.
  • “Model” represents the real world object and provides data to the “View”.

The “Controller” is responsible to take the end user request, and load the appropriate “Model” and “View”.
Question 2:
Explain MVC application life cycle.
Note: There is nothing as such called as MVC life cycle. I think a lot of people are obsessed with ASP.NET page life cycle and they think there is life cycle in MVC as well. To be specific the MVC request goes through various steps of execution and that’s what is termed as 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 appropriate Response as shown in Figure 6.2. 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. Below is the detail 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 route table with routes collection. This filling of route table happens in the global.asax file.
Step 2 – Fetch route: Depending on the URL sent “UriRoutingModule” 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 Response object: This phase has two steps executing the action and finally sending the response as a result to the view.
Step 5 – Execute Action: The “ControllerActioninvoker” determines which action to be executed and executes the action.
Step 6 – Result sent: The action method executes and creates the type of result which can be a view result, file result, json (JavaScript Object Notation) result, etc.

So in all there are six broad steps which get executed in MVC application life cycle.

Note: In case you are not able to remember the above steps during interview remember the acronym FFRCER(Fight For Respect Can Evoke Revolution).

Question 3:
Is MVC suitable for both Windows and Web application?
MVC architecture is suited for Web application than windows. For window application MVP, i.e., “Model View Presenter” is more applicable. If you are using WPF and Silverlight, MWM is more suitable due to bindings.

Question 4:
What are the benefits of using MVC?
There are two big benefits of MVC:

  • 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.
  • Automated Ul testing is possible because now the behind code (Ul interaction code) has moved to a simple.NET class. This gives us opportunity to write unit tests and automate manual testing.

Question 5:
Is MVC different from a 3-layered architecture?
MVC is an evolution of a 3-layered traditional architecture as shown in Figure 6.3. Many components of 3-layered architecture are part of MVC. So Table below shows how the mapping goes.

Functionality 3-layered / tiered architecture Model view controller architecture
Look and Feel
Ul logic
Business logic /validations Request is first sent to Accessing data
User interface
User interface
Middle layer
User interface
Data access layer
Data access layer

Question 6:
What is the latest version of MVC?
MVC 6 is the latest version which is also termed as ASP vNext.

Question 7:
What is the difference between each version of MVC 2, 3,4, 5 and 6?
ASP.NET MVC and Web API have been merged into 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 an open source via the .NET Foundation and is taking public contributions.
vNext (and Roslyn) also run on Mono, on both Mac and Linux today.
Attribute-based routing.
Asp.Net identity.
Bootstrap in the MVC template.
Authentication filters.
Filter overrides.
ASP.NET Web API (Application Programming Interface)
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. ValidationSununary 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

Question 8:
What are HTML helpers in MVC?
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.

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

Question 9:
What is the difference between “HTML.TextBox” vs “HTML.TextBoxFor”?
Both 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.

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

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

Question 10:
Explain the importance of MVC model binders.
Model binder maps HTML form elements to the model as shown in Figure 6.4. It acts like a bridge between HTML Ul and MVC model.

Take the below simple HTML form example:

Now this form needs to fill the below “Customer” class model. If you see the HTML control name they are different from the class property name. For example HTML textbox control name is “CCode” and the class property name is “CustomerCode”. This mapping code is written in HTML binder classes.

To create a model binder we need to implement “iModelBinder” interface and mapping code needs to be written in the “BindModel” method as shown in the below code.

Now in the action result method we need to use the “ModelBinder” attribute which will attach the binder with the class model.

Question 11:
What are routing in MVC?
Routing helps you to define user friendly URL (Uniform Resource Locator) structure and map those URL structure to the controller.
For instance let’s say we want that when any user types “HTTP: //localhost/View/ViewCustomer/”, it goes to the “Customer” Controller and invokes “DisplayCustomer” 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.

Question 12:
Where is the route mapping code written?
The route mapping code is written in “” file and registered using “global.asax” application start event.

Question 13:
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.

Question 14:
Explain attribute-based routing in MVC.
This is a feature introduced in MVC 5. By 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”.

Question 15:
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 “” 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.

This is much user friendly as compared to scrolling through the “” file and going through the length line of code to figure out which URL structure is mapped to which action.

Question 16:
How can we navigate from one view to other view using hyperlink?
By using “ActionLink” method as shown in the below code. The below code will create a simple URL which help to navigate to the “Home” controller and invoke the “GotoHome” action.

Question 17:
How can we restrict MVC actions to be invoked only by GET or POST?
We can decorate the MVC action by “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.

Question 18:
How can we maintain session in MVC?
Sessions can be maintained in MVC by three ways tempdata, viewdata and viewbag as shown in Figure 6.5.

Question 19:
What is the difference between tempdata, viewdata and viewbag?


  • Tempdata: Tempdata maintains data until its read. So once you set tempdata until it is not read the data is maintained in every request.

Note: In the next question we have talked about “peek” and “keep” which interviewer can ask to make you confuse more on “TempData” do read more about the same.

  • View Data: Helps to maintain data when you move from controller to view.
  • View Bag: It is a dynamic wrapper around view data. When you use “View Bag” typecasting is not required. It uses the dynamic keyword internally as shown in Figure 6.6.
  • Session variables: Session variables maintain data for a complete session that means right from the browser session started till the browser is closed.
  • Hidden fields and HTML controls: Helps to maintain data from Ul (User Interface) to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

Question 20:
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.

Question 21:
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.

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.

Question 22:
What are partial views in MVC?
Partial view is a reusable view (like a user control) which can be embedded inside other view. For example, let’s say all your pages of your site have a standard structure with Left Menu, Header and Footer as shown in the Figure 6.7.
For every page you would like to reuse the Left Menu, Header and Footer controls. So you can go and create partial views for each of these items and then you call that partial view in the main view.

Question 23:
How did you create partial view and consume the same?
When you add a view to your project you need to check the “Create a partial view (.ascx)” check box.
Once the partial view is created you can then call the partial view in the main view using “Html.RenderPartial” method as shown in the below code snippet.

Question 24:
How can we do validations in MVC?
One of the easy ways of doing validation in MVC is by using data annotations. Data’annotations are nothing but attributes which you can be applied on the model properties. For example in the below code snippet we have a simple “Customer” class with a property “CustomerCode”.
This “CustomerCode” property is tagged with a “Required” data annotation attribute. In other words if this model is not provided customer code it will not accept the same.

In order to display the validation error message we need to use “ValidateMessageFor” method which belongs to the “Html” helper class.

Later in the controller we can check if the model is proper or not by using “ModelState. IsValid” property and accordingly we can take actions.

Figure 6.9 is a simple view of how the error message is displayed on the view.
Question 25:
Can we display all errors in one go?
Yes we can, use “ValidationSummary” method from HTML helper class.

Question 26:
What are the other data annotation attributes for validation in MVC?
If you want to check string length, you can use “StringLength”.

In case you want to use regular expression, you can use “RegularExpression” attribute.

If you want to check whether the numbers are in range, you can use the “Range” attribute.

Some time you would like to compare value of one field with other field, we can use the “Compare” attribute.

In case you want to get a particular error message, you can use the “Errors” collection.

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.

In case you want add errors in the controller you can use “AddModelError” function.

Question 27:
How can we enable data annotation validation on client-side?
It’s a two-step process. In first step, give reference the necessary j query files.

Second step is to call “EnabieCiientValidation” method.

Question 28:
Explain Areas in MVC.
Areas help you to group functionalities Into independent modules thus making your project more organized. For example, in the Figure 6.10 MVC project is shown where we have four controller classes and as time passes by if more controller classes are added it will be difficult to manage. In bigger projects you will end up with 100’s of controller classes making life hell for maintenance.
If we group controller classes into logical section like “Invoicing” and “Accounting” that would make life easier and that’s what “Areas” are meant to as shown in Figure 6.13
You can add an area by right clicking on the MVC solution and clicking on “Area…” menu as shown in the Figure 6.12.
In the Figure 6.13, we have two “Areas” created “Accounts” and “Invoicing” and in that I have put the respective controllers. You can see how the project is looking more organized as compared to the previous state.
Question 29:
What is Razor in MVC?
It’s a lightweight view engine. Till MVC we had only one view type, i.e., ASPX, Razor was introduced in MVC 3.

Question 30:
Why Razor when we already had 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.

In Razor it’s just one line of code.

Question 31:
So which is a better fit Razor or ASPX?
Microsoft Razor is more preferred because it’s lightweight and has simple syntaxes.

Question 32:
Explain the difference between layout and master pages.
Layout are like master pages in ASP.NET Web form. Master pages give a standard look and feel for Web form views while layout gives standard look and feel or acts like a template for Razor views.

Question 33:
How to apply layout to Razor views?
So first we need to create a template file as shown in the below code.

And then apply this template to the view as shown below and display data in those respective sections.

Question 34:
Explain the concept of Scaffolding.
Note: Do not get scared with the word. Its actually a very simple thing.

Scaffolding is a technique in which the MVC template helps to auto-generate CRUD code. CRUD stands for Create, Read, Update and Delete.
So to generate code using scaffolding technique we need to select one of the types of templates (leave the empty one) as shown in Figure 6.14.
For instance if you choose “using Entity Framework” template as shown in Figure 6.15 the following code is generated.
It creates controller code, view and also table structure as shewn in the Figure 6.16.
Question 35:
What does scaffolding use internally to connect to database?
It uses Entity Framework internally.

Question 36:
How can you do authentication and authorization in MVC?
You can use windows or forms authentication for MVC.

Question 37:
How to implement Windows authentication for MVC?
For windows authentication you need to go and modify the “Web.config” file and set authentication mode to Windows.

Then in the controller or on the action you can use the “Authorize” attribute which specifies the users who can access these controllers and actions. Below is the code snippet for the same. Now only the users specified in the controller and action can access the same.

Question 38:
How do you implement forms authentication in MVC?
Forms authentication is implemented the same way as we do in ASP.NET. So the first step is to set authentication mode equal to forms. The “loginUrl” points to a controller here rather than page.

We also need to create a controller where we will check the user is (authorized) proper or not. If the user is proper (authorized) we will set the cookie value.

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

Question 39:
How to implement Ajax in MVC?
You can implement Ajax in two ways in MVC:

  • Ajax libraries
  • jQuery (a cross-platform JavaScript)

Below is a simple sample of how to implement Ajax by using “Ajax” helper library. In the below code you can see we have a simple form which is created by using “Ajax.BeginForm” syntax. This form calls a controller action called as “getCustomer”. So now the Submit action click will be an asynchronous Ajax call.

In case you want to make Ajax calls on hyperlink clicks you can use “Ajax.ActionLink” function as shown in the Figure 6.17.
So if you want to create Ajax asynchronous hyperlink by name “GetDate” which calls the “GetDate” function on the controller, below is the code for the same. Once the controller responds this data is displayed in the HTML Divtag by name “DateDiv”.

Below is the controller code. You can see how “GetDate” function has a pause of 10 seconds.

The second way of making Ajax cal! in MVC is by using jQuery. In the below code you can see we are making an Ajax POST call to a URL “/MyAjax/getCustomer”. This is done by using “$ .post”. All this logic is put in to a function called as “GetData” and you can make a call to the “GetData” function on a button or a hyperlink click event as you want.

Question 40:
What kind of events can be tracked in Ajax?
There are 4 events which can be tracked as shown in the Figure 6.18.
Question 41:
What are the different types of results in MVC?
Note: It’s difficult to remember aii the twelve types. But some important ones you can remember for the interview are “ActionResuit”, “ViewResult” and “JsonResult”. Below is a detailed list for your interest.
There twelve kinds of results in MVC, at the top is ”ActionResult”class which is a base class that can have eleven subtypess as listed below.

  1. ViewResult – Renders a specified view to the response stream.
  2. PartialviewResult – Renders a specified partial view to the response stream.
  3. EmptyResult – An empty response is returned.
  4. RedirectResult – Performs an HTTP (HyperText Transfer Protocol) redirection to a specified URL.
  5. RedirectToRouteResult – Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data.
  6. JsonResult – Serializes a given object to json
  7. JavaScriptResult – Returns a piece of JavaScript code that can be executed on the client.
  8. Content Result – Writes content to the response stream without requiring a view.
  9. FileContentResult – Returns a file to the client.
  10. FileStreamResult – Returns a file to the client, which is provided by a Stream.
  11. FilePathResult – Returns a file to the client.

Question 42:
What are “ActionFilters”in MVC?
“ActionFilters” helps you to perform logic while MVC action is executing or after a MVC action has executed as shown in Figure 6.19.
Action filters are useful in the following scenarios:

  1. Implement post-processing logic before the action happens.
  2. Cancel a current execution.
  3. inspect the returned value.
  4. Provide extra data to the action.

You can create action filters by two ways:

  • Inline action filter.
  • Creating an “ActionFilter”

To create a inline action attribute we need to implement “iActionFilter” interface. The “IActionFilter” interface has two methods “OnActionExecuted” and “OnActionExecuting”. We can implement pre-processing logic or cancellation logic in these methods.

The problem with inline action attribute is that it cannot be reused across controllers. So we can convert the inline action filter to an action filter attribute. To create an action filter attribute we need to inherit from “ActionFilterAttribute” and implement “IActionFilter” interface as shown in the below code.

Later we can decorate the controllers on which we want the action attribute to execute. You can see in the below code I have decorated the “DefaultlController” with “MyActionAttribute” class which was created in the previous code.

Question 43:
What is the difference between “ActionResult” and “ViewResult”?
“ActionResult” is an abstract class while “ViewResult” derives from “ActionResult” class. “ActionResult” has several derived classes like “ViewResult”, ” JsonResult”, “FileStreamResult” and so on.
“ActionResult” can be used to exploit polymorphism and dynamism. So if you are returning different types of view dynamically “ActionResult” is the best thing. For example in the below code snippet you can see we have a simple action called as “Dynamicview”. Depending on the flag (“IsHtmlView”) it will either return “ViewResult” or “JsonResult”.

Question 44:
What are the different types of action filters?

  1. Authorization filters
  2. Action filters
  3. Result filters
  4. Exception filters

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

  1. Authorization filters
  2. Action filters
  3. Response filters
  4. Exception filters

Question 46:
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 following 3 steps:
Let’ say we want to create a custom view engine where in the user can type a command like “<DateTime>” and it should display the current date and time.
Step 1: We need to create a class which implements “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 the same.

Step 2: We need to create a class which inherits from “VirtualPathProviderViewEngine” 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 CustomView we need to provide an extension. Below is how the code looks like. You can see the “ViewLocationFormats” is set to the “Views” folder and the extension is ” .myview”.

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 the same.

Below is a simple output format of the CusiomView written using the commands defined at the top as shown in Figure 6.20.
If you invoke this view you should see the following output as shown in Figure 6.21.
Question 47:
How to emit JSON from MVC?
In MVC we have “JsonResult” class by which we can return back data in JSON format. Below is a sample code which returns back “Customer” object in JSON format using “JsonResult”.

Figure 6.22 shows the JSON (JavaScript Object Notation) output of the above code if you invoke the action via the browser.
Question 48:
What is “WebAPl”?
HTTP is the most used protocol. For past many years browser was the most preferred client by which we can consume data exposed over HTTP. But as years passed by client variety started spreading out. We had demand to consume data on HTTP from clients like mobile, JavaScripts, Windows application, etc.
For satisfying the broad range of client ReSTor “rest” (Representational State Transfer) was the proposed approach. You can read more about “REST” from WCF chapter.
“WebAPI” is the technology by which you can expose data over HTTP following REST principles.

Question 49:
How does WCF differ from WEB API?

Multi-protocol hosting Heavy weight because of complicated WSDL (Web Services Description Language) structure. Lightweight, only the necessary information is transferred.
Protocol Independent of protocols. Only for HTTP protocol.
Formats To parse SOAP (Simple Object Access Protocol) message, the client needs to understand WSDL format. Writing custom code for parsing WSDL is a heavy duty task. If your client is smart enough to create proxy objects like how we have in .NET (add reference) then SOAP is easier to consume and call. Output of “WebAPI” are simple string message, JSON, Simple XML format etc. So writing parsing logic for the same in very easy.
Principles SOAP follows WS-* specification. WebAPI follows REST principles. (Please refer about REST in WCF chapter).

Question 50:
With WCF also you can implement REST, so why “WebAPI”?
WCF was brought in to implement SOA, never the intention was to implement REST.”WebAPI’” is built from scratch and the only goal is to create HTTP services using REST. Due to the one point focus for creating “REST” service “WebAPI” is more preferred.

Question 51:
How to implement “WebAPI” in MVC?
Below are the steps to implement “WebAPI”:
Step1: Create the project using the “WebAPI” template as shown in Figure 6.23.
Step 2: Once you have created the project you will notice that the controller now inherits from “ApiController” and you can now implement “POST”, “GETt”, “PUT” and “DELETE” methods of HTTP protocol.

Step 3: If you make a HTTP GET call you should get the results as shown in Figure 6.24.
Question 52:
How can we detect that a MVC controller is called by POST or GET?
To detect if the call on the controller is “POST” action or a “GET” action we can use “Request. HTTPMethod” property as shown in the below code snippet.

Question 53:
What is bundling and minification in MVC?
Bundling and minification help us to improve request load time of a page thus increasing performance. How does bundling increase performance?
Web projects always need CSS (Cascading Style Sheet) and script files. Bundling helps us to combine to multiple JavaScript and CSS file into a single entity thus minimizing multiple requests into a single request.
For example consider the below Web request to a page. This page consumes two JavaScript files “JavaScriptl.js” and “JavaScript2.js”. So when this is page is requested it makes three request calls as shown in Figure 6.25:

  • One for the “Index” page.
  • Two requests for the other two JavaScript files “JavaScriptl .js” and “JavaScript2.js”.

Below scenario can become worst if we have lot of JavaScript files resulting in many multiple requests thus decreasing performance. If we can somehow combine all the JS files into a single bundle and request them as a single unit that would result in increased performance. (See the Figure 6.26 which has a single request.
Question 54:
So how do we implement bundling in MVC?
Open the “” from the “App_Start” folder as shown in Figure 6.27.
In the “” add the JS files which you want bundle into single entity form the bundles collection. In the below code we are combining all the JavaScript JS files which are existing in the “Scripts” folder as a single unit in to the bundle collection.

Below is how your “” file will look like.

Once you have combined your scripts into one single unit we then to include all the JS files in to the view using the below code. The below code needs to put in the ASPX (Active Server Page Extended) or RAZOR view.
Razor is an ASP.NET programming syntax used to create dynamic Web page with the C# or Visual Basic.

If you now see your page requests you would see that script request is combined into a one request (See Figure 6.26).

Question 55:
How can you test bundling in debug mode?
If you are in a debug mode you need to set “EnableOptimizations” to true in the “” file or else you will not see the bundling effect in the page requests.

Question 56:
Explain minification and how to implement the same.
Minification reduces the size of script and CSS files by removing blankspaces, comments, etc. For example below is a simple JavaScript code with comments.

// This is test
var x = 0;
X = X + 1 ;
x = x * 2 ;

After implementing minification the JavaScript code looks something as below. You can see how whitespaces and comments are removed to minimize file size and thus increasing performance.

Question 57:
How to implement minification?
When you implement bundling minification is implemented by itself. In other words steps to implement bundling and minification are same.

Question 58:
Explain the concept of View Model in MVC.
A view model is a simple class which represents data to be displayed on the view.
For example below is a simple Customer model object with “CustomerName” and “Amount” properties.

But when this “Customer” model object is displayed on the MVC view it looks something as shown in the Figure 6.28. It has “CustomerName”, “Amount” plus “Customer buying level” fields on the view / screen as shown in Figure 6.28. “Customer buying level” is a color indication which indicates how aggressive the customer is buying.
“Customer buying level” color depends on the value of the “Amount property. If the amount is greater than 2000 then color is red, if amount is greater than 1500 then color is orange or else the color is yellow.
In other words “Customer buying level” is an extra property which is calculated on the basis of Amount. So the CustomerViewModel class has three properties as summarized in Table 6.1.

  • “TxtCustomerName” textbox takes data from “CustomerName” property as it is.
  • “TxtAmount” textbox takes data from “Amount” property of model as it is.
  • “CustomerBuyingLevelColor” displays color value depending on the “Amount”

Question 59:
How can we use two ( multiple) models with a single view?
Let us first try to understand what the interviewer is asking. When we bind a model with a view we use the model drop-down as shown in the Figure 6.29. In the Figure we can only select one model.
But what if we want to bind “Customer” class as well as “Order” class to the view.
For that we need to create a view model which aggregates both the classes as shown in the below code. And then bind that view model with the view.

In the view we can refer both the model using the view model as shown in the below code.

Question 60:
What kind of logic view model class will have?
As the name says view model this class has the gel code (Bridge 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 Ul (User Interface) 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 Ul you would like to display it as a checkbox which is checked if “married” and unchecked if “unmarried”.
  • Aggregation logic: You have two different Customer 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.

Question 61:
What is the use of “AllowHTML” and “Validatelnput” attributes?
While working with MVC you may have noticed that MVC actions doesn’t allow posting HTML (HyperText Markup Language) values. This is done to avoid cross site scripting security issues. Look at the example given in Figure 6.30 where we are trying to post HTML to the MVC action.
But you can bypass this restriction by using one of the following two attributes:

  1. Validatelnput attribute at controller level or action level (See Figure 6.31).
  1. AllowHtml attribute at mode level (See Figure 6.32).


Question 62:
Explain unobtrusive JavaScript.
Unobtrusive JavaScript helps you to decouple presentation and behavior. Consider the below button code it has two parts: one is the UI, i.e., the button itself and second is the behavior, i.e.,”ShowAlert()
In other words the button is tied up with the “ShowAlert” action. It would be great if we could decouple the behavior from the button so that any other behavior can be attached with the button.

Look at this button code you can see no action is attached with the below button element.

Action to the button is attached on runtime as shown in the below code. If needed tomorrow we can attach some other behavior with “btn” button. So unobtrusive JavaScript is nothing but decoupling the presentation from the behavior.

Question 63:
Explain the need of display mode in MVC?
Display mode displays views depending on the device the user has logged in with. So we can create different views for different devices anddisplay mode will handle the rest.
For example we can create a view “Home.aspx’ Home.Mobile.aspx for mobile devices as shown in to the MVC application, display mode checks the “user agent” headers and renders the appropriate view to the device accordingly.

Question 64:
How can we validate using Facebook or Twitter accounts (MVC OAuth)?
One of the most boring processes for an end user is registering^ on a site. Sometimes those long forms and e-mail validation just puts off the user. So how about making things easy by validating the users using their existing Facebook, Twitter, Linkedin, etc., accounts. So the user uses something which he/she already has while the site is assured that this user is an authorized user.
This is achieved by using MVC OAuth (Open Standard for Authorization).Using MVC O Auth is a three step process:

  • Register your MVC application / Website with the external site, i.e., facebook, twitter, etc. Once you register your app you get an ID and key from the external site. Figure 6.35 shows how Facebook gives the App ID and Key. In Facebook they term the key as the “App Secret”. This process varies from site to site. So Facebook can have X steps while Twitter can X+1.
  • Next step is to open “” arid you will see lot of readymade code to user your ID and Key. So use the appropriate method as per site, and provide the ID and Key.
  • Now if you run your application you should get a link to Facebook login as shown in the Figure 6.36. So if you login in Facebook it will redirect to your MVC application.

Question 65:
What is the use of ActionName in MVC?
Answered in the next question.

Question 66:
Can we overload Actions / Controllers in MVC?
Let us first try to understand what interviewer is asking. If you have a controller as shown in the below code snippet and in the controller if you have overloaded methods will it work. For example in the below “Customer” controller we have two “LoadCu-stomer () ” methods one with a parameter and one without a parameter.
So will this work. The answer is No.

If you try to invoked “LoadCustomer” you get an error as shown in Figure 6.37.
In order to resolve the same you decorate one of your actions with “ActionName” attribute as shown in the below code.

So now if you make a call to URL (Uniform Resource Locator) “Customer/LoadCustomer” the “LoadCustomer” action will be invoked and with URL structure “Customer/ LoadCustomerByName” the “LoadCustomer (string str) ” will be invoked.

Question 67:
How can we do exception handling in MVC?
There are six ways by which you can achieve exception handling in MVC.
Method 1: Simple way
The simplest way is to use the traditional .NET exception handling style, i.e., try and catch block. Now when exception happens catch block gets executed and it redirects to the error view.
But if we use this method then we will not be utilizing MVC exception mechanism properly and completely. In the further sections we will discuss five important ways by which we can utilize MVC provided features for exception handling.

Method 2: Override “OnException” method
In this method we can override the “OnException” event and set the “Result” to the view name. This view gets invoked when error occurs in this controller. 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.

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

The problem with this approach is we cannot reuse the error handling logic across multiple controllers.

Method 3: Using “HandleError” Attribute
The other way of handling error is using “HandleError” attribute. Implementing ‘jHandleError” attribute is a two-step process:
Step 1: We need to first decorate the action method with “HandleError” attribute as shown in the below code.

Step 2: In the “Web.config” file you need to add the “customErrors” tag and point to the “Error” view as shown in the below “Web.config” code snippet.

In case you want different error views for different exception types you can decorate action method with multiple “HandleError” attribute point to multiple views as per exception types.

Method 4: Inheriting from “HandleErrorAttribute”
One of the biggest drawbacks of all the previous method was reusability. Error handling logic cannot be reused across other controllers.
In order to reuse error handling logic across controller we can inherit from “HandleErrorAttribute” class and decorate this class as attribute across controller.

Method 5: Handling HTTP errors
All MVC exception handling techniques discussed till now do not handle HTTP (HyperText Transfer Protocol) errors like file not found, HTTP 500 error, (Internal Server Error) etc. For that we need to make an entry of the error action and the error status code as shown in the below config file.

Method 6: Global Error handling in MVC
If you wish to do global error handling across your application you can override the “Application_Error” event and do a Response. Redirect from the global error event. So if the error handling is not done at the controller level it will get propagated to “Global.asax” file.

The best is combination of “Method 4” and “Method 6”. Create error handling classes which inherit from “HandleError At tribute” class and decorate them respectively on controllers and action methods. So this takes care of errors happening on controllers and actions.
As a safety enable’Global error handling as a fallback for any unexpected and unhandled errors by using “Application_Error” event as described in “Method 6”.

Question 68:
How to handle multiple Submit buttons in MVC?
Let us elaborate on what the interviewer is asking.
Take a scenario where you have a view with two Submit buttons as shown in the below code.

In the above code when the end user clicks on any of the Submit buttons it will make a HTTP POST to “Action 1”.
The question from the interviewer is:
“What if we have want that on “Submitl” button click it should invoke “ActionT’ and on the “Submit2” button click it should invoke “Action2’’.”
There are three basic approaches to solve the above problem scenario.
Using HTML:
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 “ActionT’ and the second form will post to “Action2” depending on which “Submit” button is clicked.

Using Ajax:
In case the interviewer complains that the above approach is not Ajax, this is where the second approach comes into picture. In the Ajax way we can create two different functions “Funl” and “Funl”, see the below code. These functions will make Ajax calls by using jQuery or any other framework. Each of these functions are binded with the “Submit” button’s “OnClick” events.

Using “Ac tionNameSelect orAt tribute”:
This is a great and a clean option. The “ActionNameSelectorAttribute” is a simple attribute class where we can write decision making logic which will decide which action can be executed.
So the first thing is in HTML we need to put proper name’s to the Submit buttons for identifying them on the server.
You can see we have put “Save” and “Delete” to the button names. Also you can notice in the action we have just put controller name “Customer” and not a particular action name. We expect the action name will be decided by “ActionNameSelectorAttribute”.

So when the Submit button is clicked, it first hits the “ActionNameSelector” attribute and then depending on which submit is fired it invokes the appropriate action as shown in Figure 6.38.
So the first step is to create a class which inherits from “ActionNameSelectorAttribute” class. In this class we have created a simple property “Name”.
We also need to override the “IsValidName” function which returns true or flase. This function is where we write the logic whether an action has to be executed or not. So if this function returns true then the action is executed or else it is not.

The main part of the above function is in the below code. The “ValueProvider” collection has all the data that has been posted from the form. So it first looks up the “Name” value and if its found in the HTTP request it returns true or else it returns false.

This attribute class can then decorated on the respective action and the respective “Name” value can be provided. So if the Submit is hitting this action and if the name matches of the HTML Submit button name it then executes the action further or else it does not.

Question 69:
What is the of AntiForgery token in MVC?
Please read the next answer for the same.

Question 70:
What is CSRF attack and how can we prevent the same in MVC?
CSRF stands for Cross Site Request Forgery. So if you see the dictonary meaning of forgery:
“It’s an act of copying or imitatingthings like signature on a cheque, official documents to deceive the authority source for financial gains. ”
So when it comes to Website this forgery is termed as CSRF (Cross Site Request Forgery).
CSRF is a method of attacking/hacking a Website where the attacker imitates a.k.a forges as a trusted source and sends data to the site. Genuine site processes the information innocently thinking that data is coming from a trusted source.
For example, consider the Figure 6.39 which shows a screen of an online bank. End user uses this screen to transfer money.
Below is a forged site created by an attacker which looks a game site from outside, but internally it hits the bank site for money transfer as shown in Figure 6.40.
The internal HTML of the forged site has those hidden fields which have the account number and amount to do transfer money.

Now let’s say the user has logged in to the genuine bank site and the attacker sent this forged game link to his/her e-mail. The end user thinking that it’s a game site clicks on the “Play the ultimate game” button and internally the malicious code does the money transfer process as shown in Figure 6.41.
So a proper solution to this issue can be solved by using tokens as shown in Figure 6.42.

  • End user browses to the screen of the money transfer. Before the screen is served server injects a secret token inside the HTML screen in form of a hidden field.
  • Now hence forth when the end user sends request back he/she has to always send the secret token. This token is validated on the server.

Implementing token is a two-step process in MVC.
First apply “ValidateAntiForgeryToken” attribute on the action.

Second in the HTML Ul screen call “@Html. AntiForgeryToken ()” to generate the token.

So now henceforth when any untrusted source sends a request to the server it would give the forgery errors ash shown in Figure 6.43.
If you do a view source of the HTML you would find the below verification token hidden field with the secret key.

Question 71:
What is XSS?
XSS (Cross Site Scripting) is a security attack where the attacker injects malicious code while doing data entry. This code can be a JavaScript, VBScript or any other scripting code. Once the code is injected in end user’s browser. This code can run and gain access to cookies, sessions, local files and so on.
For instance Figure 6.44 shows a simple product data entry form. You can see in the product description how the attacker has injected a JavaScript code.
Once we click submit you can see the JavaScript code actually running as shown in Figure 6.45.
Question 72:
How can we prevent the same in MVC?
In MVC by default XSS attack is validated. So if any one tries to post JavaScript or HTML code he she gets an error as shown in Figure 6.46.
Question 73:
What is the difference between “Validatelnput” and “AllowHTML” in MVC?
As said in the previous question in ASP.NET MVC we are not allowed to postscripts and HTML code by default. But consider the situation as shown in Figure 6.47 where we want HTML to be written and submitted.
The other scenario where we need HTML to be posted is HTML editors. So there is always a need now and then to post HTML to the server.So for those kinds of scenarios where we want HTML to be posted we can decorate the action with “Vaiidatelnput” set to false. This bypasses the HTML and Script tag checks for that action.
You can see in the below code we have requested the MVC framework to not validate the input to the action.

But the above solution is not proper and neat. It opens a complete Pandora box of security issues. In this product screen scenario we just HTML in product description and not in product name as shown in Figure 648.
But because we have now decorated validate false at the action level, you can also write HTML in product name field as well.
That’s where “AIIowhtml” comes to help. You can see in the below code we have just decorated the “ProductDescription” property .

And from the action we have removed “Vaiidatelnput” attribute.

If you now try to post HTML in product name field you will get an error saying you cannot post HTML tags in product name field as shown in Figure 6.49.
So the difference between Vaiidatelnput and AllowHtml is the granularity of preventing XSS attacks.
Below are some more practical questions which are asked frequently. I am thankful to Mr Lalit Kale ( HTTPs: // to collect the same and put it forward.

About the author


Leave a Comment