Skip to content

Instantly share code, notes, and snippets.

@sphingu
Created June 19, 2013 09:18
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sphingu/5812932 to your computer and use it in GitHub Desktop.
Save sphingu/5812932 to your computer and use it in GitHub Desktop.
MVC Interview Questions

Interview Question


1.In which assembly is the MVC framework defined? System.Web.Mvc

2.What is ViewData, ViewBag and TempData?

  MVC offers Three options for passing data from controller to View and  in next request. 
ViewData & ViewBag are almost similar.
  	Short life means value becomes null when redirection occurs.
		It’s a communication mechanism within the server call.
Difference between ViewBag & ViewData:
		ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
		ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
		ViewData requires typecasting for complex data type and check for null values to avoid error.
		ViewBag doesn’t require typecasting for complex data type.
 		 ViewBag.Name = "Sumit Hingu";
 		 ViewData["Name"] = "Sumit Hingu";
TempData performs additional resposibility.
		TempData is also a dictionary derived from TempDataDictionary class
		The difference is that the life cycle of the object.
		when you move from one controller to other controller or from one action to other action. In other words when you redirect, “Tempdata” helps to maintain data between those redirects
		It internally uses session variables.
    

3.What is Lambda Expression?

A Lambda Expression is an anonymous function that can contain expressions and statement and can be used to create delegates or expression tree types.

4.What is JSON?

  JavaScript Object Notation.
syntax for storing and exchanging text information.Much like XML.
lightweight text-data interchange format
smaller than XML, and faster and easier to parse.
Language Independent
Self Describing and easy to understand.
JSON uses JavaScript syntax for describing data objects, but JSON is still language and platform independent. JSON parsers and JSON libraries exists for many different programming languages.
  

5.How to use Cookie in MVC.

  		HttpCookie cook = new HttpCookie("Transfer");
           //usually you put here more , but now I do not want to interfere with other methods
           cook.Expires = DateTime.Now.AddSeconds(1);
           cook.Value = "from transfer cookies";
           Response.Cookies.Add(cook);

6.How to use Session in MVC

Layout pages, can define sections, which can then be overriden by specific views making use of the layout. Defining and overriding sections is optional.
//adding data to session
//assuming the method below will return list of Products

var products=Db.GetProducts();

//Store the products to a session

Session["products"]=products;

//To get what you have stored to a session

var products=Session["products"] as List;

//to clear the session value

Session["products"]=null;

6.What is Area in MVC?

Areas it is possible to "isolate" the modules of your site.
ReportsAreaRegistration.cs, this file is used to configure the routing system for the area.

7.What's the deal with values parameter in ASP.NET MVC?

return RedirectToAction(actionName: "Action", routeValues: new { id = 99 });
  1. How do you specify comments using razor syntax?
@{
    //This is a comment
}

@{/*
      This is a multi
      line comment
*/}

@*
      This is a comment, as well
*@

9.What are the file extensions for razor views?

.cshtml or .vbhtml

10.What is Section in MVC?

@RenderSection(string sectionName, bool required)

@section SectionName { } 
 
IsSectionDefined("SideBar") Method Return boolean value

11.Master Page in Razor MVC?

Master Page in Razor
Views/Shared/_Layout.cshtml

Difine Default MasterPage in Razor
Views/_ViewStart.cshtml
  @{
    	Layout = "~/Views/Shared/_Layout.cshtml";
	}

12.How to Protect MVC from Cross Side Scripting(XSS)?

No, by default content emitted using a @ block is automatically HTML encoded to protect from cross site scripting (XSS) attacks.

  [AllowHtml] at model Property
	[ValidateInput(false)] at Action method
	Use AntiXSS nuget Package 
	in Method write  string Text=Sanitizer.GetSafeHtmlFragment(text);
  1. In razor syntax, what is the escape sequence character for @ symbol?
The escape sequence character for @ symbol, is another @ symbol

14.What symbol would you use to denote, the start of a code block in razor views?

@ - for razor
<%= %> -  for aspx

15.What type of filter does OutputCacheAttribute class represents?

Result Filter

16.Filters run in the following order:

Authorization filters
Action filters
Response filters
Exception filters

17.example for Authorization filters in an asp.net mvc application

RequireHttpsAttribute 
AuthorizeAttribute

18.Give 2 examples for scenarios when routing is not applied?

i) A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by setting the RouteExistingFiles property of the RouteCollection object to true. 
ii) Routing Is Explicitly Disabled for a URL Pattern - By using the RouteCollection.Ignore() method, you can prevent routing from handling certain requests.
 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 

19.What are the 2 ways of adding constraints to a route?

Use regular expressions
Use an object that implements IRouteConstraint interface  

20.Is there any way to handle variable number of segments in a route definition ?

You can handle variable number of segments in a route definition by using a route with a catch-all parameter. 
Example: 

controller/{action}/{*parametervalues} 

Here * reffers to catch-all parameter.

21.What is the difference between adding routes, to a webforms application and to an mvc application?

To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class, where as to add routes to an MVC application we use MapRoute() method.

22.What is the use of the following default route?

{resource}.axd/{*pathInfo}
This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.

23.What are the 3 things that are needed to specify a route?

1. URL Pattern - You can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.
2. Handler - The handler can be a physical file such as an .aspx file or a controller class.
3. Name for the Route - Name is optional.

24.Advantage of Routing in mvc?

Without using Routing in an ASP.NET MVC application, the incoming browser request should be mapped to a physical file.The thing is that if the file is not there, then you will get a page not found error. 
By using Routing, it will make use of URLs where there is no need of mapping to specific files in a web site. 
This is because, for the URL, there is no need to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users.

25.ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are these 2 places?

1. Web.Config File : ASP.NET routing has to be enabled here.
2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax file.
  1. What are the 3 segments of the default route, that is present in an ASP.NET MVC application?
1st Segment - Controller Name
2nd Segment - Action Method Name
3rd Segment - Parameter that is passed to the action method

27.Where are the routing rules defined in an asp.net MVC application?

In Application_Start event in Global.asax

28.What is the role of a controller in an MVC application?

The controller responds to user interactions, with the application, by selecting the action method to execute and alse selecting the view to render.
  1. Is it possible to share a view across multiple controllers?
Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.

30.What is the significance of NonActionAttribute?

In general, all public methods of a controller class are treated as action methods. If you want prevent this default behaviour, just decorate the public method with NonActionAttribute.

31.Name a few different return types of a controller action method?

The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.
1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult

32.What is the greatest advantage of using asp.net mvc over asp.net webforms?

It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.

33.What does Model, View and Controller represent in an MVC application?

Model: Model represents the application data domain. In short the applications business logic is contained with in the model.

View: Views represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI.

Controller: Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface. The user input logic is contained with in the controller.

34.What are the advantages of ASP.NET MVC?

1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
2. Complex applications can be easily managed
3. Seperation of concerns. Different aspects of the application can be divided into Model, View and Controller.
4. ASP.NET MVC views are light weight, as they donot use viewstate.

35.What is the ‘page lifecycle’ of an ASP.NET MVC?

Following process are performed by ASP.Net MVC page:
1) App initialization
2) Routing
3) Instantiate and execute controller
4) Locate and invoke controller action
5) Instantiate and render view

36.How route table is created in ASP.NET MVC?

When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.

37.What is the use of action filters in an MVC application?

Action Filters allow us to add pre-action and post-action behavior to controller action methods.

38.What are the levels at which filters can be applied in an asp.net mvc application?

1. Action Method
2. Controller
3. Application

39.What is Routing?

A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a Web Forms application. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment