ASP.NET MVC Interview Questions: Part 1

Initially I will focus on ASP.NET MVC interview questions and here are few of them starting from today. In upcoming articles, I will keep on adding fresh questions and intent will be to cover up all those scenarios which you may encounter in an interview. Here we go,

Question: Suppose you want to use a partial view but also pass the same model object from the parent view, what HTML Helper would you use?

Answer: Html.Partial() method provide by MVC.

Question: How can we create a dynamically generated form for an entire object based upon the metadata of the object's type using MVC engine.

Answer: We can use Html.EditorForModel() for this purpose, then we do not need to pass the model to the helper as a parameter because it reads directly from the view. For more deep understanding you can go through the following images:

parameter

Output after rendering.

Output

Question: What is the use of OutputCacheAttribute in MVC?

Answer: The best use of this attribute is to mark an action method whose output will be cached.

Question: You have restricted a Controller so that all actions require the user to be authorized. Now an unauthorized user want to access a specific action so what will be your approach in order to use without authorization?

Answer: You should decorate that particular action with AllowAnonymous attribute.

  1. [AllowAnonymous]   
  2. public ActionResult WelCome(string DotnetPiper)   
  3. {   
  4.    return View();   
  5. }   
Question: Advantages of MVC Model and ASP.NET Web Forms model. Difference between MVC and Web Forms!

Answer: Here are some main advantages which may help you to understand which model may be the best for your requirement.

 

  1. MVC provides clean separation of concerns (SoC).
  2. MVC allows full control over the rendered HTML you can do amendments as your need.
  3. Enable Test Driven Development (TDD) and easy to test.
  4. Easy integration with JavaScript frameworks which enables rich features.
  5. Support third-party view engines.No ViewState and PostBack events so it is stateless nature of web.
  6. URL based approach which is famous as Routing.

Advantages of Web Form Model

  1. Provides Rapid action development.
  2. Provides rich controls.Easy development model and event driven.
  3. Familiar model for windows form developers.

To explore MVC further, I am sharing some interesting facts about the similarities and dissimilarities of MVC and Web Forms.

I have seen many articles stating dissimilarities between both, however I will also list some similarities.

ASP.NET MVC / Web Forms Similarities

The following are some similarities; they both:

  1. Are built on the ASP.Net Framework.
  2. Are in the System.Web namespace.
  3. Use .Net Framework supported languages.
  4. Use an IIS and ASP.Net request Pipeline, for example HTTP Handler and HTTP Module.
  5. Send the response back to the client in the form of HTML.
  6. Also support third-party controls.

ASP.NET MVC / Web Forms dissimilarities

The following are some dissimilarities.

ASP.NET MVC

ASP.Net Web Forms

View and logic are separate, it has separation of concerns theory. MVC 3 onwards has .aspx page as .cshtml. No separation of concerns; Views are tightly coupled with logic (.aspx.cs /.vb file).
Introduced concept of routing for route based URL. Routing is declared in Global.asax for example. File-based routing .Redirection is based on pages.
Support Razor syntax as well as .aspx Support web forms syntax only
State management handled via Tempdata, ViewBag, and View Data. Since the controller and view are not dependent and also since there is no view state concept in ASP.NET, MVC keeps the pages lightweight. State management handled via View State. Large viewstate, in other words increase in page size.
Partial Views User Controls
HTML Helpers Server Controls
Multiple pages can have the same controller to satisfy their requirements. A controller may have multiple Actions (method name inside the controllerclass). Each page has its own code, in other words direct dependency on code. For example DotnetPiper.aspx is dependent on Dotnetpiper.aspx.cs (code behind) file
Unit Testing is quite easier than ASP.NET Web forms Since a web form and code are separate files. Direct dependency, tight coupling raises issues in testing.
URL based Event Driven
layouts Master Pages

I hope these facts may help you to understand the similarities and dissimilarities between MVC and Web Forms. I tried to keep it simple to understand the fact in an easier manner.

Question: TempData, Keep and Peek methods in MVC4 and its uses practically.

Answer: An intention to write something on these keywords Keep and Peek to abolish confusion. Here are the definition of Keep and Peek method:

  • Keep-> It marks the specified keys to keep in dictionary memory.
  • Peek-> it returns an object contains an element without marking object for deletion in Dictionary.

Let’s look at a practical approach and abolish confusion if someone has. TempData value persist at successive request and can transmit from Controller to View. After transferring TempData value from controller to View, if you again try to use it at other level than it will lost its value and become null. TempData is used to pass data from current request to subsequent request from one level to another level e.g. controller to view, controller to controller. One action to another action. I’ve two action methods of a same controller and performed some steps in order to verify the authenticity of methods.

  1. public ActionResult Verify()  
  2. {  
  3.    ICollection<ModelState> collection = ModelState.Values;  
  4.    //return View("Verify", dbContext.EmpRegistrations.Single(x => x.Id == 111111));  
  5.    if (TempData["EmployeeRegistration"] != null)  
  6.    {  
  7.       TempData["EmployeeRegistration"] = ObjEmp.GetEmpRegistrationsDetails();  
  8.       TempData.Keep("EmployeeRegistration");  
  9.    }  
  10.    else  
  11.    {  
  12.       TempData["EmployeeRegistration"] = ObjEmp.GetEmpRegistrationsDetails();  
  13.       TempData.Keep("EmployeeRegistration");  
  14.    }  
  15.    return View("Verify", TempData["EmployeeRegistration"]);  
  16. }  
  1. public ActionResult Details(int id)  
  2. {  
  3.    var checkViewDataValue = TempData.Peek("EmployeeRegistration");  
  4.    return View();  
  5. }  
When I start execution with Verify action it sets its value in TempData and used Keep method to retain its value for further cycle as you can see in Verify action.

Now in the Details action I have brought in the value in variable from TempData using Keep method. However if I hit the same URL (http://localhost:60346/Register/Details/1) again to verify its value existence than it doesn’t retain as shown below in image:

Details action

To retain its value again you have to use Keep method again. Because the key in TempData dictionary is marked for deletion when it is read and is deleted at the end of HTTP Request. On the other hand, Peek method is used to read data from TempData without marking the key in the dictionary for deletion.
  1. public ActionResult Details(int id)  
  2. {  
  3.    var checkViewDataValue = TempData.Peek("EmployeeRegistration");  
  4.    return View();   
  5. }  
If you are retrieving the data using Peek method, then their is no need to retain data using Keep method again and again. Peek is best in use to retrieve data from TempData. This was the question that is generally asked in an Interview.

Stay Tuned for more questions

Question: How can we handle exception in MVC4 and at how many level?

Answer: We have a HandleError Attribute to handle the errors. You can handle an error at the following different levels:
  1. Global Level
  2. Controller level
  3. Action Level

In the following code snippet, various ways to define and handle an error is provided.

The HandleError Attribute filter works only when custom errors are enabled in the Web.config file of your application. You can enable custom errors by adding a customErrors attribute inside the <system.web> node, as depicted below:

  1. <customErrors mode="On" defaultRedirect="Error" />  
This is the way to handle an error at Global Level.
  1. public static void RegisterGlobalFilters(GlobalFilterCollection filters)  
  2. {  
  3.    //Register multiple filters are applied with ascending Order (default = -1)  
  4.   
  5.    //database errors  
  6. filters.Add(new HandleErrorAttribute  
  7. {  
  8.    ExceptionType = typeof(System.Exception),  
  9.    View = "Error"// Shared folder error page //Error.cshtml  
  10.    Order = 1  
  11. });  
  12. filters.Add(new HandleErrorAttribute() { Order = 1 });  
  13. }  
HandleError attribute @ Action level:
  1. [HandleError(ExceptionType = typeof(System.InvalidOperationException), View = "Error")]  
  2. public ActionResult Verify()  
  3. {  
  4.    ICollection<ModelState> collection = ModelState.Values;  
  5.    return View("Verify", dbContext.EmpRegistrations.Single(x => x.Id == 111111));  
  6. }  
And this is same way to defined attribute at Controller level.

So whenever you execute your Controller/action or it generates an error, then it redirects to Error.cshtml page and shows you a custom error as in the following screenshot:

execute

Question: How can we override the action names in MVC?

Answer: If we want to override the action names we can do like this –
  1. [ActionName("DotnetPiper")]  
  2. public ActionResult VerifyAction() {  
  3.    return View();  
  4. }  
Question: How to restrict the users to request the method/Action directly in the browser's URL?

Answer: There are probably certain ways to achieve the result .Two of them are shown below:

Option 1

Using ChildActionMethod allows you to restrict access to action methods that you would not want users to directly request in the browser's URL.
  1. [ChildActionOnly]  
  2. public ActionResult DotnetPiper()  
  3. {   
  4.    return View();  
  5. }  
To know more in depth please visit this link : CHILD ACTION METHODS IN ASP.NET MVC4.

Option 2

In ASP.NET MVC each method of controller is access by URL and in case we have created an action which should not be accessible via URL, then MVC provides you way to protect your action method via NonAction attribute.

After declaring method as NonAction if you want to access method/action via url. It will return HTTP 404 not found error.
  1. [NonAction]  
  2. public ActionResult DotnetPiper()  
  3. {   
  4.    return "DotnetPiper.com";\  
  5. }  
Question: What is the difference between ActionResult and ViewResult()?

Answer:

ActionResult is an abstract class and it is base class for ViewResult class.ActionResult is a general result type that can have several subtypes such as ViewResult, PartialViewResult, JsonResult, ContentResult, etc.

ViewResult is an implementation for this abstract class. It finds a view page .cshtml or .aspx in some predefined paths in view folder like (/views/controllername/, /views/shared/, etc) by the given view name.

If you are sure that your action method will return some view page, you can use ViewResult and definitely maybe it is possible that if action method may have different behavior other than view like Redirect to Action, Content Result, you should use the base class ActionResult as the return type.

Question: How we can overload the action in MVC?

Answer: If we want to overload the action names we can do like the following code snippet:
  1. public ActionResult VerifyAction()  {  
  2.         return Content("Welcome to DotnetPiper");  
  3.     }   
  4.     [ActionName("DotnetPiper")]  
  5. public ActionResult VerifyAction() {  
  6.     return Content("Welcome to DotnetPiper");   
  7. }  
To access above overload method please type the following URL in the web browser:

http://localhost:57964/Home/DotnetPiper

Question: If there are two controllers exists with the same name in a solution than how ASP.Net MVC handles such scenario.

Answer: ASP.NET provides you way to resolve such issue after putting Namespace as a parameter at the time of defining Route. Kindly refer the following image to understand how it actually works:

code
  1. routes.MapRoute(  
  2.     "DefaultRegister"// Route name  
  3.     "{controller}/{action}/{id}"// URL with parameters  
  4.     new {  
  5.         controller = "Register", action = "Verify", id = UrlParameter.Optional  
  6.     }, // Parameter defaults  
  7.     new [] {  
  8.         "MVCSample.Controllers"  
  9.     } // Namespaces  
  10. );  
Question: Which base class can be used for the return value of an MVC action method?

Answer: ActionResult

Question: Which of these formats is not supported out of the box by Web API?

Answer: Form URL-encoded, JSON and XML.

Execution order of filters in MVC 4 with practices: important faq.

There are the following types of filters that can be implemented to inject custom processing logic.
  • Authorization filter
  • Action filter
  • Result filter
  • Exception filter

In MVC 5 a new filter has been added Authentication. The order of execution will be the following if we add that also:

  • Authentication Filter
  • Authorization filter
  • Action filter
  • Result filter
  • Exception filter

For more detail, here's the link:

How can you restrict access to a Controller, action?

Answer: You can restrict access to a Controller, action using Authorize attribute so that only authorized users can made an attempt to it.

Question: What is the type of the ViewBag property?

Answer: Dynamic

Question: If you have a _Layout.cshtml file in your shared views, which file can you create to have custom layout for mobile platforms?

Answer: _Layout.mobile.cshtml

Question: What is ChildActionOnlyAttribute?

Answer: A Method that is decorated with ChildActionOnlyAttribute can be called only with the Action or RenderAction HTML extension methods.

Kindly add your valuable thoughts if you feel that it could be done in a better way.