ASP.NET MVC (Model View Controller) Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on ASP.NET MVC (Model View Controller)

Note: In case you are new to MVC and you want to kick start learning MVC we would recommend you to go 
through 5 videos provided in the “Learn MVC Step by Step” section.
Lab 1: Simple Hello world.
Lab 2: Explain MVC Routing.
Lab 3: Explain ViewData, ViewBag, TempData & Session.
Lab 4: Explain Model and Strongly typed views.
Lab 5: Explain Model Binders.

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

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 1

  • The “View” is responsible for the 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”.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 2

Question 2.
Explain the MVC application life cycle.
Answer:

Note: There is nothing as such called an MVC life cycle. I think a lot of people are obsessed with the ASP.NET
 page life cycle and they think there is a 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 the MVC application life cycle.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 3

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 a detailed 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 routing table with routes collection. This filling of the routing table happens in the global.asax file.

Step 2 – Fetch route: Depending on the URL sent “UrlRoutingModule” searches the routing table to create a “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 the “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 “ControllerActionlnvoker” 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 that get executed in the MVC application life cycle.

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

Question 3.
Is MVC suitable for both Windows and Web applications?
Answer:
MVC architecture is suited for Web applications 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?
Answer:
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 the opportunity to write unit tests and automate manual testing.

Question 5.
Is MVC different from a 3-layered architecture?
Answer:
MVC is an evolution of a 3-layered traditional architecture as shown in Figure 6.3. Many components of the 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 User interface View
Ul logic User interface Controller
Business logic /validations Middle layer Model
The request is first sent to User interface Controller
Accessing data Data access layer Data access layer

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 4

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

Question 6.
What is the difference between each version of MVC 2, 3,4, 5, and 6?
Answer:
MVC 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 is 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.
The compilation is done with the new Roslyn real-time compiler.
vNext is open-source via the .NET Foundation and is taking public contributions.
vNext (and Roslyn) also run on Mono, on both Mac and Linux today.

MVC 5
OneASP.NET.
Attribute-based routing.
Asp.Net identity.
Bootstrap in the MVC template.
Authentication filters.
Filter overrides.

MVC 4
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.

MVC 3
Razor
Readymade project templates.
HTML 5 enabled templates.
Support for multiple view Engines.
JavaScript and Ajax.
Model validation improvements.

MVC 2
Client-side validation.
Templated helpers.
Areas.
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

Question 7.
What are HTML helpers in MVC?
Answer:
HTML helpers help you to render HTML controls in the view. For instance, if you want to display an HTML textbox on the view, below is the HTML helper code.

<%= Html. TextBox(“LastName’) %>

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

<%= Html.CheckBox(“Married”) %>

Question 8.
What is the difference between “HTML.TextBox” vs “HTML.TextBoxFor”?
Answer:
Both provide the same HTML output, “Html .TextBoxFor” is strongly typed while “Html .TextBox” isn’t.
Below is a simple HTML code that just creates a simple textbox with “CustomerCode” as a 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”.

Question 9.
Explain the importance of MVC model binders.
Answer:
Model binder maps HTML form elements to the model as shown in Figure 6.4. It acts as a bridge between HTML Ul and MVC model.
Take the below simple HTML form example:

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 5

<formid="frml" method=post action="/Customer/SubmitCustomer">
             Customer code: <inputname="CCode"type="text"/>
             Customer name: <inputname="CName''type="text"/>
            <input type=submit/>
</form>

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.

publicclassCustomer
{
     publicstring CustomerCode { get; set; }
     publicstring CustomerName { get; set; }
}

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.

publicclassCustomerBinder: IModelBinder
{
       publicobject BindModel(ControllerContext controllerContext,
       ModelBindingContext bindingContext)
       {
            HTTPRequestBase request = controllerContext.HTTPContext.Request;
            string strCustomerCode = request.Form.Get("CCode");
            string strCustomerName = request.Form.Get("CName");

            returnnewCustomer
            {
                 CustomerCode = strCustomerCode,
                 CustomerName = strCustomerName
           } ;
      }
}

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

publicActionResult SubmitCustomer([ModelBinder(typeof(CustomerBinder))] Customer obj) 
{
        return View("DisplayCustomer");
}

Question 10.
What are routing in MVC?
Answer:
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.

routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "Display-Customer", id
= UrlParameter.Optional }); // Parameter defaults

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

Question 12.
Can we map multiple URL’s to the same action?
Answer:
Yes, you can, you just need to make two entries with different key names and specify the same controller and action.

Question 13.
Explain attribute-based routing in MVC.
Answer:
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”.

public class HomeController: Controller
{
       [Route("Users/about")]
       public ActionResult GotoAbout()
       {
            return View( );
       }
}

Question 14.
What is the advantage of defining route structures in the code?
Answer:
Most of the time developers code in the action methods. Developers can see the URL structure right upfront rather than going to the “routeconfig.es” 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 “routeconfig.es” file and going through the length line of code to figure out which URL structure is mapped to which action.

public class HomeController: Controller
{
       [Route("Users/about")]
       [Route("Users/WhoareWe")]
       [Route("Users/OurTeam")]
       [Rout("Users/aboutCompany")]
       public ActionResult GotoAbout()
       {
            return View( );
       }
}

Question 15.
How can we navigate from one view to other view using hyperlink?
Answer:
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.

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

Question 16.
How can we restrict MVC actions to be invoked only by GET or POST?
Answer:
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.

[HTTPGet]
public ViewResult DisplayCustomer(int id)
{
       Customer objCustomer = Customers[id];
       return View("DisplayCustomer", objCustomer);
}

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

Question 18.
What is the difference between tempdata, viewdata and viewbag?
Answer:

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 6

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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 7

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 19.
What is life of “TempData”?
Answer:
“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 20.
What is the use of Keep and Peek in “TempData”?
Answer:
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( );

Question 21.
What are partial views in MVC?
Answer:
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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 8

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 22.
How did you create partial view and consume the same?
Answer:
When you add a view to your project you need to check the “Create a partial view (.ascx)’’ check box.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 9

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.

<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>

Question 23.
How can we do validations in MVC?
Answer:
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.

public class Customer
{
       [Required(ErrorMessage="Customer code is required")]
       public string CustomerCode
       {
            set;
            get;
       }
}

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

<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
<input type="submit" value="Submit customer data" />
<%}%>

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.

public ActionResult PostCustomer(Customer obj)
{
      if (ModelState.IsValid)
      {
           obj.Save();
           return View("Thanks");
      }
      else
      {
          return View("Customer");
      }
}

Figure 6.9 is a simple view of how the error message is displayed on the view.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 10

Question 24.
Can we display all errors in one go?
Answer:
Yes we can, use “ValidationSummary” method from HTML helper class.

<%= Html. ValidationSummary( ) %>

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

[StringLength( 160)]
public string FirstName { get; set;}

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

[RegularExpression(@”[A-Za-zO-9._%+-]+@[A-Za-zO-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.

[Range(10, 25)] 
public int Age { get; set;}

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

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.

var ErrMessage = ModelState[“Emaii”].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.

TryUpdateModel(NewCustomer);

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

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

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

<script src="<%= Url.Content("-/Scripts/jQuery-1.5.1.js") %>" type="text/ j avascript"x/script>
<script src="<%= Url.Content("-/Scripts/jQuery.validate.js") %>" type="text/ javascript"x/script>
<script src="<%= Url.Content("-/Scripts/jQuery.validate.unobtrusive.j s") %>" type = "text/javascript"x/script>

Second step is to call “EnableClientValidation” method.

<% Html.EnableClientValidationO; %>

Question 27.
Explain Areas in MVC.
Answer:
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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 11

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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 12

You can add an area by right clicking on the MVC solution and clicking on “Area…” menu as shown in the Figure 6.12.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 13

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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 14

Question 28.
What is Razor in MVC?
Answer:
It’s a lightweight view engine. Till MVC we had only one view type, i.e., ASPX, Razor was introduced in MVC 3.

Question 29.
Why Razor when we already had ASPX?
Answer:
Razor is clean, lightweight and syntaxes are easy as compared to ASPX. For example in ASPX to display simple time we need to write.

<%=Date Time. Now%>

In Razor it’s just one line of code.

@DateTime.Now

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

Question 31.
Explain the difference between layout and master pages.
Answer:
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 32.
How to apply layout to Razor views?
ANswer:
So first we need to create a template file as shown in the below code.

<div>
@RenderSection("Header")
@RenderBody( )
@RenderSection("Footer")
</div>

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

@{Layout = "~/Views/Defaultl/_LayoutPagel.cshtml";}
This is body
@section Footer{Copyright 2015-2016}
@section Header{Welcome to my site}

Question 33.
Explain the concept of Scaffolding.
Answer:

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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 15

For instance if you choose “using Entity Framework” template as shown in Figure 6.15 the following code is generated.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 16

It creates controller code, view and also table structure as shown in the Figure 6.16.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 17

Question 34.
What does scaffolding use internally to connect to database?
ANswer:
It uses Entity Framework internally.

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

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

<authentication mode="Windows"/>
<authorization>
<deny users = "?''/>
</authorization>

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.

[Authorize(Users= @"WIN-3LI600MWLQN\Administrator"),
public class StartController: Controller
{
       //
      // GET: /Start/
      [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
      public ActionResult Index()
      {
              return View("MyView");
      }
}

Question 37.
How do you implement forms authentication in MVC?
Answer:
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.

<authentication mode="Forms">
<forms loginUrl="~/Home/Login" timeout="2880"/>
</authentication>

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.

public ActionResult Login( )
{
       if ((Request.Form["txtUserName"] == "Shiv") &&
       (Request.Form["txtPassword"] == "Shiv@123"))
       {
              FormsAuthentication.SetAuthCookie("Shiv", true);
              return View("About");
      }
      else
      {
             return View("Index");
      }
}

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.

[Authorize]
PublicActionResult Default ( )
{
      return View( );
}
[Authorize]
PublicActionResult About( )
{
     return View();
}

Question 38.
How to implement Ajax in MVC?
Answer:
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.

<script language="javascript">
function OnSuccess(data1)
{
       // Do something here
}
</script>
<div>
<%
        var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};
%>
<% using (Ajax.BeginForm("getCustomer", "MyAjax", AjaxOpt}) { %>
<input id="txtCustomerCode" type="text" /xbr />
<input id="txtCustomerName" type="text" /xbr />
<input. id="Submit2" type="submit" value= "submit"/></div>
<%} %>

In case you want to make Ajax calls on hyperlink clicks <X you can use “Ajax. ActionLink” function as shown Aj
in the Figure 6.17.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 18

So if you want to create Ajax asynchronous hyperlink by name “GetDate” which calls the “GetDate” function v» on the controller, below is the code for the same. Once the controller responds this data is displayed in the HTML
DIV tag by name “DateDiv”.

<span id=”DateDiv” />
<%:
Ajax.ActionLink(“Get Date”, “GetDate”,
new AjaxOptions (UpdateTargetld = “DateDiv” })
%>

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

public class DefaultlController: Controller
{
      public string GetDate( )
      {
          Thread.Sleep(10000);
          return DateTime2Now.ToString( );
      }
}

The second way of making Ajax call 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.

function GetData( )
{
      var url = "/MyAjax/getCustomer";
      $.post(url, function (data)
     {
                $("#txtCustomerCode").val(data.CustomerCode) ;
                $("#txtCustomerName").val(data.CustomerName);
     }
}

Question 39.
What kind of events can be tracked in Ajax?
Answer:

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 19

Question 39.
What is the difference between “ActionResult” and “ViewResult”?
Answer:
“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”.

public ActionResult DynamicView(bool IsHtmlView)
{
      if (IsHtmlView)
      return View(); // returns simple ViewResult
      else
      return Json( ); // returns JsonResult view
}

Question 40.
What are the different types of results in MVC?
Answer:

Note: It’s difficult to remember all the twelve types. But some important ones you can remember 
for the interview are “ActionResult”, “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 format.
  7. javaScriptResult – Returns a piece of JavaScript code that can be executed on the client.
  8. Content Re suit – Writes content to the response stream without requiring a view.
  9. FileContentResuit – 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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 20

Question 41.
What are “ActionFilters”in MVC?
Answer:
“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” attribute.

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.

public class DefaultlController: Controller, IActionFilter
{
         public ActionResult Index(Customer obj)
        {
                 return View(obj);
        }
        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {
            Trace.WriteLine("Action Executed");
        }
       void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
           Trace.WriteLine("Action is executing");
       }
}

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.

public class MyActionAttribute: ActionFilterAttribute, IActionFilter
{
        void IActionFilter.OnActionExecuted(ActionExecutedContext
        filterContext)
        {
                 Trace .WriteLine ( "Action Executed");
        }
       void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
       {
                 Trace.WriteLipe("Action executing");
      }
}

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.

[MyActionAttribute]
public class DefaultlController: Controller
{
      public ActionResult Index(Customer obj)
      {
             return View(obj);
      }
}

Question 42.
What are the different types of action filters?
Answer:

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

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

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

Question 44.
Can we create our custom view engine using MVC?
Answer:
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.

public class MyCustomView: IView
{
       private string _FolderPath; // Define where our views are stored
       public string FolderPath
       {
             get { return _FolderPath; }
             set { _FolderPath = value; }
       }
       public void Render(ViewContext viewContext, System.10.TextWriter writer) ‘
       {
            // Parsing logic <dateTime>
           // read the view file
          string strFileData = File.ReadAllText(_FolderPath);
         //we need to and replace <datetime> datetime.now value
        string strFinal = strFileData.Replace("<DateTime>",
        DateTime.Now.ToString());
       // this replaced data has to sent for display
       writer.Write(strFinal);
     }
}

Step 2: We need to create a class which inherits from “VirtualPathProviderViewEngine” and in this class we need to provide the FolderPath 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”.

public class MyViewEngineProvider: VirtualPathProviderViewEngine
{
      //We will create the object of Mycustom view
      public MyViewEngineProvider() // constructor
      {
             // Define the location of the View file
             this.ViewLocationFormats = new string[ ] { "-/Views/{1}/
             {0}.myview", "-/Views/Shared/{0}.myview" }; //location and 
             extension of our views
      }
      protected override IView CreateView(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 parsing logic so that it can 
             be registered in the view engine collection
     }
protected override IView CreatePartialView(ControllerContext 
controllerContext, string partialPath)
{
            var physicalpath =
            controllerContext.HTTPContext.Server.MapPath(partialPath);
            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 parsing 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 the same.

protected void Application_Start( )
{
     // Step3: register this object in the view engine collection
     ViewEngines.Engines.Add(new MyViewEngineProvider());
     ......
}

Below is a simple output format of the CustomView written using the commands defined at the top as shown in Figure 6.20.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 21

If you invoke this view you should see the following output as shown in Figure 6.21.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 22

Question 45.
How to emit JSON from MVC?
Answer:
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”.

public JsonResult getCustomer()
{
      Customer obj = new Customer();
      obj .CustomerCode = "1001";
      obj.CustomerName = "Shiv";
      return Json(obj, JsonRequestBehavior.AllowGet);
}

Figure 6.22 shows the JSON (JavaScript Object Notation) output of the above code if you invoke the action via the browser.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 23

Question 46.
What is “WebAPI”?
Answer:
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 47.
How does WCF differ from WEB API?
Answer:

WCF 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 48.
With WCF also you can implement REST, so why “WebAPI”?
Answer:
WCF was brought in to implement SOA, never the intention was to implement REST.”WebAPH 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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 24

Question 49.
How to implement “WebAPI” in MVC?
Answer:
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.

public class ValuesController: ApiController
{
       // GET api/values
       public IEnumerable<string> Get( )
       {
            return new string [ ] { "value1" , "value2" } ;
       }
       // GET api/values/5
       public string Get(int id)
       {
             return "value";
       }
       //POST api/values
       public void post { [ Frombody ] string value ]
       {
       }
       // PUT api/values/5
       public void Put(int id, [FromBody ] string value ]
       {
       }
      // DELETE api/values/5
       public void Delete(int id)
       {
       }
}

Step 3: If you make a HTTP GET call you should get the results as shown in Figure 6.24.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 25

Question 50.
How can we detect that a MVC controller is called by POST or GET?
Answer:
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.

public ActionResult SomeAction()
{
      if (Request.HTTPMethod == "POST")
      {
           return View("SomePage");
      }
      else
      {
      return View("SomeOtherPage");
      }
}

Question 51.
What is bundling and minification in MVC?
Answer:
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 “JavaScriptljs” 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”.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 26

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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 27

Question 52.
So how do we implement bundling in MVC?
Answer:
Open the “BundleConfig.es” from the “App Start” folder as shown in Figure 6.27.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 28

In the “BundleConfig.es” 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.

bundles.Add(new ScriptBundle(“~/Scripts/MyScripts”).lnclude(
“-/Scripts/*.js”));

Below is how your “BundleConfig.es” file will look like.

public class BundleConfig
{
       public static void RegisterBundles(BundleCollection bundles)
       {
              bundles.Add(new ScriptBundle("-/Scripts/MyScripts").Include( . "-/Scripts/*.j s"));
              BundleTable.EnableOptimizations = true;
      }
}

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.

<%= Scripts.Render(“~/Scripts/MyScripts”) %>

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

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

BundleTable.EnableOptimizations = true;

Question 54.
Explain minification and how to implement the same.
Answer:
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.

var x=0;x=x+ 1;x=x*2;

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

Question 56.
Explain the concept of View Model in MVC.
Answer:
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.

CustomerViewModel pbj = new CustomerViewModel(); 
obj.Customer.CustomerName = "Shiv";
obj.Customer,Amount = 1000;

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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 29

“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” value.
Customer Model Customer View Model
Customer Name TXt Customer Name
Amount TXt Amount

Customer Buying Levelcolor

Question 57.
How can we use two ( multiple) models with a single view?
ANswer:
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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 30

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.

public class CustOrderVM 
{
        public Customer cust = new Customer( ); 
        public Order Ord = new Order();
} 

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

<%= model.oust.Name %>
<%- model. Ord.Number %>

Question 58.
What kind of logic view model class will have?
Answer:
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 59.
What is the use of “AllowHTML” and “Validatelnput” attributes?
Answer:
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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 31

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

[HttpPost()]
[Validatelnput(false)]
public ActionKesult Index(ArticleData o)
{
return View(o);
}

2. AllowHtml attribute at mode level (See Figure 6.32).

public claw* .ArticleOsta
{
, [AllowHtffllO )
public string ArticleContent { get; set; } public string ArticleTitle { get; set; }
}

Question 60.
Explain unobtrusive JavaScript.
Answer:
Unobtrusive JavaScript helps you to decouple presentation and behavior. Consider the below button code it has two parts: one is the Ul, 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 decoup’– the behavior from the button so that any other behavior can be attached with the button.

<input type="button" onclick="ShowAlert()" id="btn" />
<script>
function ShowAlert( )
{
       alert("Hello");
}
</script>

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

<input type=”button ” id= ”btn ” />

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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 32

<script>
function ShowAlert()
{
alert("Hello");
}
var el =
document.getElementByld("btn");
el.onclick = ShowAlert;
</script>

Question 61.
Explain the need of display mode in MVC?
Answer:
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” which will render for the desktop computers and Home.Mobile.aspx for mobile devices as shown in Figure 6.33. Now when an end user sends a request to the MVC application, display mode checks the “user agent” headers and renders the appropriate view to the device accordingly.

Question 62.
How can we validate using Facebook or Twitter accounts (MVC OAuth)?
Answer:
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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 33

This is achieved by using MVC OAuth (Open Standard for Authorization).
Using MVC 0 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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 34

  • Next step is to open “AuthConfig.es” and 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.
OAuthWebSecurity.RegisterMicrosoftClient( 
       clientld: 
       clientSecret:
OAuthWebSecurity.RegisterTwitterClient(
      consumerKey: "" , 
      consumerSecret: " ");
OAuthWebSecurity.RegisterFacebookClient(
       appld: " ",
       appSecret: "");
OAuthWebSecurity.RegisterGoogleClient( );
  • 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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 35

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

Question 64.
Can we overload Actions / Controllers in MVC?
Answer:
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 “LoadCustomer {)” methods one with a parameter and one without a parameter.
So will this work. The answer is No.

public class CustomerController: Controller
{
     //
    // GET: /Customer/
    public ActionResult LoadCustomer( )
    {
          return Content("LoadCustomer");
    }
    public ActionResult LoadCustomer(string str)
    {
          return Content("LoadCustomer with a string");
    }
}

If you try to invoked “LoadCustomer” you get an error as shown in Figure 6.37.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 36

In order to resolve the same you decorate one of your actions with “ActionName” attribute as shown in the below code.

public class CustomerController: Controller
{
       //
      // GET: /Customer/
      public ActionResult LoadCustomer( )
      {
           return Content("LoadCustomer");
      }
      [ActionName("LoadCustomerbyName")]
      public ActionResult LoadCustomer(string str)
      {
            return Content("LoadCustomer with a string");
      }
}

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

Question 65.
How can we do exception handling in MVC?
Answer:
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.

public ActionResult SomeKrror()
{
      try
      ( )
      catch(Exception ex)
      {return View("Error");}
}

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.

public class HomeController: Controller
{
       protected override void OnException(ExceptionContext filterContext)
       {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;
          
            var model = new HandleErrorlnfo(filterContext.Exception,
            "Controller", "Action");

            filterContext.Result = new ViewResult( )
            {
                    ViewName = "Error",
                    ViewData = new ViewDataDictionary(model)
            };
      }
}

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

@Model. Exception;

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

Method 3: Using nHandleError” Attribute
The other way of handling error is using “HandleError” attribute. Implementing “HandleError” 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.

public class HomeController: Controller
{
         [HandleError()]
          public ActionResult SomeErrorf)
          {
                 throw new Exception("test");
          }
}

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.

<system.Web>
<customErrors defaultRedirect="Error.cshtml" mode="On">
</customErrors>
</system.Web>

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.

public class HomeController: Controller
{
       [HandleError(ExceptionType=typeof(ArithmeticException), 
       View="Arthimetic")]
       [HandleError(ExceptionType = typeof(NotlmplementedException), View ="Error1")]
       public ActionResult SomeError( )
       {
       }
}

Method 4: Inheriting from nHandleErrorAttribute”
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.

public class Err: HandleErrorAttribute
{
       public override void OnException(ExceptionContext filterContext)
       {
              Exception ex = filterContext.Exception;
              filterContext.ExceptionHandled = true; '
              var model = new HandleErrorInfo(filterContext.Exception, 
              "Controller", "Action");

              filterContext.Result = new ViewResult( )
              {
                      ViewName = "Error1",
                      ViewData = new ViewDataDictionary(model)
              };
       }
}

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.

<system.Web> 
<customErrors
            mode="On" defaultRedirect="Error1">
<error statusCode="404" redirect="~/Testing/NoPageFound"/>
</customErrors>
</system.Web>

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.

public class MvcApplication: System.Web.HTTPApplication
{
       protected void Application_Error(object sender, EventArgs e)
       {
              Exception exception = Server.GetLastError( );
              Server.ClearError( );
              Response.Redirect("/Home/Error");
       }
}

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 ”Appiication_Error” event as described in “Method 6”.

Question 66.
How to handle multiple Submit buttons in MVC?
Answer:
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.

<form action="Actionl" method=post> 
<input type="submit" name="Submitl"/>
<input type="submit" name="Submit2"> .
</form>

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 “SubmitT’ button click it should invoke “Actionl” 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 “Actionl” and the second form will post to “Action2” depending on which “Submit” button is clicked.

<form action="Action1" method=post> 
<input type="submit" name="Submit1"/>
</form> 
<form action="Action2" method=post>
<input type="submit" name="Submit2">
</form>

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.

<Script language="javascript">
function Fun1( )
{
      $.post("/Action1", null, CallBack1);
}
function Fun2( )
{
      $.post("/Action2", null, CallBack2);
}
</Script>
<form action="/Action1" method=post>
<input type=submit name=sub1 onclick="Fun2( )"/>
</form>
<form action="/Action2" method=post>
<input type=submit name=sub2 onclick="Funl()"/>
</form>

Using “ActionNameSelectorAttribute”:
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”.

<form action="Customer" method=post>
<input type=submit value="Save" name="Save" /xbr />
<input type=submit value="Delete" name="Delete"/>
</form>

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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 37

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

public class SubmitButtonSelector: ActionNameSelectorAttribute
{
       public string Name { get; set; }
       public override bool IsValidName(ControllerContext controllerContext, 
       string actionName, System.Reflection.Methodlnfo methodlnfo)
{
       // Try to find out if the name exists in the data sent from form
       var value =
       controllerContext.Controller.ValueProvider.GetValue(Name); 
       if (value != null)
       {
              return true;
       }
       return false;
    }
}

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.

var value = controllerContext.Controller.ValueProvider.GetValue(Name); if (value != null)
{
       return true;
}
return 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.

public class CustomerController: Controller
{
       [SubmitButtonSelector(Name="Save")]
       public ActionResult Save( )
       {
      return Content("Save Called");
     }
       [SubmitButtonSelector(Name = "Delete")]
        public ActionResult Delete()
      {
            return Content("Delete Called");
     }
}

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

Question 68.
What is CSRF attack and how can we prevent the same in MVC?
Answer:
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).

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 38

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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 39

The internal HTML of the forged site has those hidden fields which have the account number and amount to do transfer money.

<div> 
Win 1000000 US$
<form action="HTTP: //localhost: 23936/Genuine/Transfer" method=post> 
<input type=hidden name="amount" value="10000” />
<input type=hidden name="account" value="3002" />
<input type=submit value="Play the ultimate game" />
</form>
</div>

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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 40

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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 41

Implementing token is a two-stap process in MVC.

First apply “ValidateAntiForgeryToken” attribute on the action.
[ValidateAntiForgeryToken]

public ActionResult Transfer()
{
      // password sending logic will be here
      return Content(Request.Form["amount"] +
      " has been transferred to account "
      + Request.-Form["account"]) ;
}

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

<div>
        Transfer money
<form action="Transfer" method=post>
       Enter Amount
<input type="text" name="amount" value="" /><br />
      Enter Account number
<input type="text" name="account" value='"' /><br />
      @Html.AntiForgeryToken()
<input type=submit value="transfer money" />
</form>
</div>

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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 42

If you do a view source of the HTML you would find the below verification token hidden field with the secret key.

<input name=" RequestVerificationToken" type="hidden"
value="7iUdhsDNpEwiZFTYrH5kp/q7j L0sZz+CSBh8mb2ebwvxMJ3eYmUZXp+uofko6ei PDO 
fmC7Q0o4SXeGgRpxFp0i+Hx3 fgVlVybgCYpyhFw5IRyYhNqi9KyH0 seOhBPRu/ 9kYwEXXnVGB9ggdXCVP 
clud/gUzjWVCvUlQxGA9dKPA=" />

Question 69.
What is XSS?
Answer:
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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 43

Once we click submit you can see the JavaScript code actually running as shown in Figure 6.45.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 44

Question 70.
How can we prevent the same in MVC?
Answer:
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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 45

Question 71.
What is the difference between “Validatelnput” and “AllowHTML” in MVC?
Answer:
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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 46

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

[Validatelnput(false)]
public ActionResult PostProduct(Product obj)
{
return View(obj);
}

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.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 47

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 “AHOWHTML” comes to help. You can see in the below code we have just decorated the “ProductDescription” property .

public class Product
{
      public string ProductName { get; set; }
      [AllowHtm1]
      public string ProductDescription { get; set; }
}

And from the action we have removed "Validatelnput" attribute.

public ActionResult PostProduct(Product obj)
{
      return View(obj);
}

If you now try to post HTML in product tags in product name field you will get an error saying you cannot post HTML as shown in Figure 6.49.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 48

So the difference between Validatelnput 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: // lalitkale.wordpress.com/) to collect the same and put it forward.

How MVC helps in unit testing while traditional ASP.NET does not?
What are extensibility features ofASP.NET mvc?
What are child actions?
What is the difference between layout and master pages?
How you can plug-in your favorite. loC (Inversion of Container) container in MVC? (7-10 years exp) What are the disadvantages of using ASP.NET MVC?
When you will suggest ASP.NET Webform should be used and when you will recommend ASP.NET MVC? (architect question)
In your opinion, what is the best way, you can use ASP.NET MVC with WCF? (architect and open ended question)