MVC

ASP.Net MVC Interview Questions and Answers 

 

About ASP.Net MVC
The ASP.Net MVC is the framework provided by Microsoft that lets you develop the applications that follows the principles of Model-View-Controller (MVC) design pattern. The .Net programmers new to MVC thinks that it is similar to WebForms Model (Normal ASP.Net), but it is far different from the WebForms programming. 
This article will tell you how to quick learn the basics of MVC along with some frequently asked interview questions and answers on ASP.Net MVC

1. What is ASP.Net MVC

The ASP.Net MVC is the framework provided by Microsoft to achieve     separation of concerns that leads to easy maintainability of the     application.
Model is supposed to handle data related activity
View deals with user interface related work
Controller is meant for managing the application flow by communicating between Model and View.

2. Why to use ASP.Net MVC

The strength of MVC (i.e. ASP.Net MVC) listed below will answer this question
  • MVC reduces the dependency between the components; this makes your code more testable.
  • MVC does not recommend use of server controls, hence the processing time required to generate HTML response is drastically reduced.
  • The integration of java script libraries like jQuery, Microsoft MVC becomes easy as compared to Webforms approach.

3. What do you mean by Razor

The Razor is the new View engine introduced in MVC 3.0.
The View engine is responsible for processing the view files [e.g. .aspx, .cshtml] in order to generate HTML response.
The previous versions of MVC were dependent on ASPX view engine. 

4. Can we use ASPX view engine in latest versions of MVC

Yes. The Recommended way is to prefer Razor View

5. What are the benefits of Razor View?

  •      The syntax for server side code is simplified
  •      The length of code is drastically reduced
  •      Razor syntax is easy to learn and reduces the complexity

6. What is the extension of Razor View file?

.cshtml (for c#) and .vbhtml (for vb)

7. How to create a Controller in MVC



Create a simple class and extend it from Controller class. The bare minimum requirement for a class to become a controller is to inherit it from ControllerBase is the class that is required to inherit to create the controller but Controller class inherits from ControllerBase.

8. How to create an Action method in MVC

Add a simple method inside a controller class with ActionResult return type.

9. How to access a view on the server   

The browser generates the request in which the information like Controller name, Action Name and Parameters are provided, when server receives this URL it resolves the Name of Controller and Action, after that it calls the specified action with provided parameters. Action normally does some processing and returns the ViewResult by specifying the view name (blank name searches according to naming conventions).

 

10. What is the default Form method (i.e. GET, POST) for an action method

GET. To change this you can add an action level attribute e.g [HttpPost]


11. What is a Filter in MVC?


When user (browser) sends a request to server an action method of a controller gets invoked; sometimes you may require executing a custom code before or after action method gets invoked, this custom code is called as Filter.


12. What are the different types of Filters in MVC?


a. Authorization filter

b. Action filter

c. Result filter

d. Exception filter

[Do not forget the order mentioned above as filters gets executed as per above mentioned sequence]



13. Explain the use of Filter with an example?


Suppose you are working on a MVC application where URL is sent in an encrypted format instead of a plain text, once encrypted URL is received by server it will ignore action parameters because of URL encryption.

To solve this issue you can create global action filter by overriding OnActionExecuting method of controller class, in this you can extract the action parameters from the encrypted URL and these parameters can be set on filterContext to send plain text parameters to the actions.    



14. What is a HTML helper?


A HTML helper is a method that returns string; return string usually is the HTML tag. The standard HTML helpers (e.g. Html.BeginForm(),Html.TextBox()) available in MVC are lightweight as it does not rely on event model or view state as that of in ASP.Net server controls.


DOTNET MVC 4 Basic Interview Questions and Answers for Freshers and Experienced Developers

Below is the list of dotnet MVC 4 basic interview questions and answers. These MVC interview questions and answers are meant for freshers as well as for experienced developers. So, If you going for an interview on MVC, I suggest you to must give a look at following MVC interview questions. These MVC interview questions are based on basic introduction to MVC, why we need MVC, components of MVC, MVC namespaces, lifecycle of MVC application and a lot more. So lets have a look on following basic dotnet MVC interview questions and answers.

1. What is MVC?

MVC is a framework methodology that divides an application’s implementation into three component roles: models, views, and controllers.

Main components of an MVC application?

1. M - Model
2. V - View
3. C - Controller

“Models” in a MVC based application are the components of the application that are responsible for maintaining state. Often this state is persisted inside a database (for example: we might have a Product class that is used to represent order data from the Products table inside SQL).

“Views” in a MVC based application are the components responsible for displaying the application’s user interface. Typically this UI is created off of the model data (for example: we might create an Product “Edit” view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object).

“Controllers” in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a MVC application the view is only about displaying information – it is the controller that handles and responds to user input and interaction.

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

3- In which assembly is the MVC framework defined?

System.Web.Mvc
4- 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.

5- Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET Webforms?

ASP.NET MVC

6- What is Razor View Engine?

Razor view engine is a new view engine created with ASP.Net MVC model using specially designed Razor parser to render the HTML out of dynamic server side code. It allows us to write Compact, Expressive, Clean and Fluid code with new syntax to include server side code in to HTML.

7- What are the advantages of ASP.NET MVC?

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. Separation 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 don't use viewstate.

8- Is it possible to unit test an MVC application without running the controllers in an ASP.NET process?

Yes, all the features in an asp.net MVC application are interface based and hence mocking is much easier. So, we don't have to run the controllers in an ASP.NET process for unit testing.

9- What is namespace of ASP.NET MVC?

ASP.NET MVC namespaces and classes are located in the System.Web.Mvc assembly.

System.Web.Mvc namespace 

Contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller factories, action results, views, partial views, and model binders.

System.Web.Mvc.Ajax namespace 

Contains classes that support Ajax scripts in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings.

System.Web.Mvc.Async namespace 

Contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application.

System.Web.Mvc.Html namespace 

Contains classes that help render HTML controls in an MVC application. The namespace includes classes that support forms, input controls, links, partial views, and validation.

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

11- 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 selecting the view to render.

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

In Application_Start event in Global.asax

13- 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

14- 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

15- 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 behavior, just decorate the public method with NonActionAttribute.

16- What is the significance of ASP.NET routing?

ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file.

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

18- 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

Example: http://google.com/search/label/MVC
Controller Name = search
Action Method Name = label
Parameter Id = MVC

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

20- What is the adavantage of using ASP.NET routing?

In an ASP.NET web application that does not make use of routing, an incoming browser request should map to a physical file. If the file does not exist, we get page not found error.

An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map to specific files in a Web site. Because the URL does not have 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.

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

22- Is the following route definition a valid route definition?

{controller}{action}/{id}
No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.

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

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

25- How do you handle variable number of segments in a route definition?

Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all parameter.
controller/{action}/{*parametervalues}

26- What are the 2 ways of adding constraints to a route?

1. Use regular expressions
2. Use an object that implements IRouteConstraint interface

27- Give 2 examples for scenarios when routing is not applied?

1. 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.
2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent routing from handling certain requests.

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

29- If I have multiple filters implemented, what is the order in which these filters get executed?

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

30- What are the different types of filters, in an asp.net mvc application?

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

31- Give an example for Authorization filters in an asp.net mvc application?

1. RequireHttpsAttribute
2. AuthorizeAttribute

32- Which filter executes first in an asp.net mvc application?

Authorization filter

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

1. Action Method
2. Controller
3. Application

34- Is it possible to create a custom filter?

Yes

35- What filters are executed in the end?

Exception Filters

36- Is it possible to cancel filter execution?

Yes

37- What type of filter does OutputCacheAttribute class represents?

Result Filter

38- What are the 2 popular asp.net mvc view engines?

1. Razor
2. .aspx

39- What is difference between Viewbag and Viewdata in ASP.NET MVC?

The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data.

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

@

41- What symbol would you use to denote, the start of a code block in aspx views?

<%= %>

In razor syntax, what is the escape sequence character for @ symbol?
The escape sequence character for @ symbol, is another @ symbol

42- When using razor views, do you have to take any special steps to protect your asp.net mvc application from cross site scripting (XSS) attacks?

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

43- When using aspx view engine, to have a consistent look and feel, across all pages of the application, we can make use of asp.net master pages. What is asp.net master pages equivalent, when using razor views?

To have a consistent look and feel when using razor views, we can make use of layout pages. Layout pages, reside in the shared folder, and are named as _Layout.cshtml

44- What are sections?

Layout pages, can define sections, which can then be overriden by specific views making use of the layout. Defining and overriding sections is optional.

45- What are the file extensions for razor views?

1. .cshtml - If the programming lanugaue is C#
2. .vbhtml - If the programming lanugaue is VB

46- How do you specify comments using razor syntax?

Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end. 

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

48- Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?

Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application.

49. How do you avoid XSS Vulnerabilities in ASP.NET MVC?

Use the syntax in ASP.NET MVC instead of using .net framework 4.0.

ASP.NET MVC Video Tutorial

Installing ASP.NET MVC - Part 1
What aspnet mvc version is my mvc application using - Part 2
Creating your first aspnet mvc application - Part 3
Part 4 Controllers in an mvc application
Part 5 Views in an mvc application
Part 6 ViewData and ViewBag in mvc
Part 7 Models in an mvc application
Part 8 Data access in mvc using entity framework
Part 9 Generate hyperlinks using actionlink html helper
Part 10 Working with multiple tables in mvc
Part 11 Using business objects as model in mvc
Part 12 Creating a view to insert data using mvc
Part 13 FormCollection in mvc
Part 14 Mapping asp.net request data to controller action simple parameter types
Part 15 Updatemodel function in mvc
Part 16 Difference between updatemodel and tryupdatemodel
Part 17 Editing a model in mvc
Part 18 Updating data in mvc
Part 19 Unintended updates in mvc
Part 20 Preventing unintended updates in mvc
Part 21 Including and excluding properties from model binding using bind attribute
Part 22 Including and excluding properties from model binding using interfaces
Part 23 Why deleting database records using get request is bad
Part 24 Deleting database records using post request in mvc
Part 25 Insert update delete in mvc using entity framework
Part 26 Customizing the autogenerated index view
Part 27 Customizing the autogenerated create view
Part 28 Customizing the autogenerated edit view
Part 29 Using data transfer object as the model in mvc
Part 30 View engines in asp net mvc
Part 31 Using custom view engines with asp net mvc
Part 32 How does a controller find a view in mvc
Part 33 Html helpers in mvc
Part 34 Generating a dropdownlist control in mvc using HTML helpers
Part 35 How to set an item selected when an asp net mvc dropdownlist is loaded
Part 36 Difference between Html TextBox and Html TextBoxFor
Part 37 Generating a radiobuttonlist control in mvc using HTML helpers
Part 38 CheckBoxList in asp net mvc
Part 39 ListBox in asp net mvc
Part 40 Using displayname, displayformat, scaffoldcolumn attributes in asp net mvc application
Part 41 Using datatype and displaycolumn attributes in asp net mvc application
Part 42 Opening a page in new browser window in asp net mvc application
Part 43 Hiddeninput and readonly attributes in mvc
Part 44 Display and edit templated helpers in asp net mvc
Part 45 Customize display and edit templates in asp net mvc
Part 46 Accessing model metadata from custom templated helpers
Part 47 Displaying images in asp net mvc
Part 48 Custom html helpers in mvc
Part 49 Html encoding in asp net mvc
Part 50 Detect errors in views at compile time
Part 51 Advantages of using strongly typed views
Part 52 Partial views in mvc
Part 53 Difference between html.partial and html.renderpartial
Part 54 T4 templates in asp net mvc
Part 55 What is cross site scripting attack
Part 56 How to prevent cross site scripting attack
Part 57 Razor views in mvc
Part 58 Razor views in mvc continued
Part 59 Layout view in mvc
Part 60 ViewStart in asp net mvc
Part 61 Named sections in layout files in mvc
Part 62 Implementing search functionality in asp net mvc
Part 63 Implement paging in asp net mvc
Part 64 Implement sorting in asp net mvc
Part 65 Deleting multiple rows in mvc
Part 66 Check uncheck all checkboxes with another single checkbox using jquery
Part 67 Action selectors in mvc
Part 68 What is the use of NonAction attribute in mvc
Part 69 Action filters in mvc
Part 70 Authorize and AllowAnonymous action filters in mvc
Part 71 childactiononly attribute in mvc
Part 72 HandleError attribute in mvc
Part 73 OutputCache attribute in mvc
Part 74 CacheProfiles in mvc
Part 75 RequireHttps attribute in mvc
Part 76 ValidateInput attribute in mvc
Part 77 Custom action filters in asp net mvc
Part 78 Different types of ActionResult in asp net mvc
Part 79 Areas in asp net mvc
Part 80 StringLength attribute in asp net mvc
Part 81 Range attribute in asp net mvc
Part 82 Creating custom validation attribute in asp net mvc
Part 83 RegularExpression attribute in asp net mvc
Part 84 Compare attribute in asp net mvc
Part 85 Enable client side validation in asp net mvc
Part 86 ValidationSummary in asp net mvc
Part 87 What is Unobtrusive JavaScript
Part 88 Unobtrusive validation in asp net mvc
Part 89 Remote validation in asp net mvc
Part 90 Remote validation in mvc when javascript is disabled
Part 91 Create a custom remote attribute and override IsValid) method
Part 92 Ajax with asp net mvc
Part 93 What is Ajax and why should we use it
Part 94 Providing visual feedback using LoadingElementId AjaxOption
Part 95 OnBegin, OnComplete, OnSuccess and OnFailure properties of AjaxOptions class
Part 96 LoadingElementDuration property of AjaxOptions class
Part 97 Implement autocomplete textbox functionality in mvc
Part 98 What is JavaScript minification
Part 99 What is CDN Content Delivery Network
Part 100 What if CDN is down
Bhavin Joshi