November 13, 2017

Srikaanth Kumar

Model View Controller MVC Interview Questions Answers


1) Explain what is Model-View-Controller?

MVC is a software architecture pattern for developing web application. It is handled by three objects Model-View-Controller.

2) Mention what does Model-View-Controller represent in an MVC application?

In an MVC model,
    Model View Controller MVC Interview Questions Answers
  • Model– It represents the application data domain. In other words applications business logic is contained within the model and is responsible for maintaining data
  • View– It represents the user interface, with which the end users communicates. In short all the user interface logic is contained within the VIEW
  • Controller– It is the controller that answers to user actions. Based on the user actions, the respective controller responds within the model and choose a view to render that display the user interface.  The user input logic is contained with-in the controller.
3) Explain in which assembly is the MVC framework is defined?

The MVC framework is defined in System.Web.Mvc.

4) List out few different return types of a controller action method?
  • View Result
  • Javascript Result
  • Redirect Result
  • Json Result
  • Content Result
5) Mention what is the difference between adding routes, to a webform application and an MVC application?

To add routes to a webform application, we can use MapPageRoute() method of the RouteCollection class, where adding routes to an MVC application, you can use MapRoute() method.

6) Mention what are the two ways to add constraints to a route?

The two methods to add constraints to a route is
  • Use regular expressions
  • Use an object that implements IRouteConstraint Interface
7) Mention what is the advantages of MVC?
  • MVC segregates your project into a different segment, and it becomes easy for developers to work on
  • It is easy to edit or change some part of your project that makes project less development and maintenance cost
  • MVC makes your project more systematic
8) Mention what “beforFilter()”,“beforeRender” and “afterFilter” functions do in Controller?
  • beforeFilter(): This function is run before every action in the controller. It’s the right place to check for an active session or inspect user permissions.
  • beforeRender(): This function is called after controller action logic, but before the view is rendered. This function is not often used, but may be required If you are calling render() manually before the end of a given action
  • afterFilter(): This function is called after every controller action, and after rendering is done. It is the last controller method to run
9) Explain the role of components Presentation, Abstraction and Control in MVC?
  • Presentation: It is the visual representation of a specific abstraction within the application
  • Abstraction: It is the business domain functionality within the application
  • Control: It is a component that keeps consistency between the abstraction within the system and their presentation to the user in addition to communicating with other controls within the system
10) Mention the advantages and disadvantages of MVC model?

AdvantagesDisadvantages
  • It represents clear separation between business logic and presentation logic
  • Each MVC object has different responsibilities
  • The development progresses in parallel
  • Easy to manage and maintain
  • All classes and object are independent of each other
  • The model pattern is little complex
  • Inefficiency of data access in view
  • With modern user interface, it is difficult to use MVC
  • You need multiple programmers for parallel development
  • Multiple technologies knowledge is required

11) Explain the role of “ActionFilters” in MVC?

In MVC “ ActionFilters” help you to execute logic while MVC action is executed or its executing.

12) Explain what are the steps for the execution of an MVC project?

The steps for the execution of an MVC project includes
  • Receive first request for the application
  • Performs routing
  • Creates MVC request handler
  • Create Controller
  • Execute Controller
  • Invoke action
  • Execute Result
13) Explain what is routing? What are the three segments for routing is important?

Routing helps you to decide a URL structure and map the URL with the Controller.

The three segments that are important for routing is
  • ControllerName
  • ActionMethodName
  • Parameter
14) Explain how routing is done in MVC pattern?

There is a group of routes called the RouteCollection, which consists of registered routes in the application.  The RegisterRoutes method records the routes in this collection.  A route defines a URL pattern and a handler to use if the request matches the pattern. The first parameter to the MapRoute method is the name of the route. The second parameter will be the pattern to which the URL matches.  The third parameter might be the default values for the placeholders if they are not determined.

15) Explain using hyperlink how you can navigate from one view to other view?

By using “ActionLink” method as shown in the below code. The below code will make a simple URL which help to navigate to the “Home” controller and invoke the “GotoHome” action.

Collapse / Copy Code

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

16) Mention how can maintain session in MVC?

Session can be maintained in MVC by three ways tempdata, viewdata, and viewbag.

17) Mention what is the difference between Temp data, View, and View Bag?
  • Temp data: It helps to maintain data when you shift from one controller to other controller.
  • View data: It helps to maintain data when you move from controller to view
  • View Bag: It’s a dynamic wrapper around view data
18) What is partial view in MVC?

Partial view in MVC renders a portion of view content. It is helpful in reducing code duplication. In simple terms, partial view allows to render a view within the parent view.

19) Explain how you can implement Ajax in MVC?

In Ajax, MVC can be implemented in two ways
  • Ajax libraries
  • Jquery
20) Mention what is the difference between “ActionResult” and “ViewResult” ?

“ActionResult” is an abstract class while “ViewResult” is derived from “AbstractResult” class.  “ActionResult” has a number of derived classes like “JsonResult”, “FileStreamResult” and “ViewResult” .

“ActionResult” is best if you are deriving different types of view dynamically.

21) Explain how you can send the result back in JSON format in MVC?

In order to send the result back in JSON format in MVC, you can use “JSONRESULT” class.

22) Explain what is the difference between View and Partial View?

View Partial View
  • It contains the layout page
  • Before any view is rendered, viewstart page is rendered
  • View might have markup tags like body, html, head, title, meta etc.
  • View is not lightweight as compare to Partial View
  • It does not contain the layout page
  • Partial view does not verify for a viewstart.cshtml. We cannot put common code for a partial view within the viewStart.cshtml.page
  • Partial view is designed specially to render within the view and just because of that it does not consist any mark up
  • We can pass a regular view to the RenderPartial method

23) List out the types of result in MVC?

In MVC, there are twelve types of results in MVC where “ActionResult” class is the main class while the 11 are their sub-types
  • ViewResult
  • PartialViewResult
  • EmptyResult
  • RedirectResult
  • RedirectToRouteResult
  • JsonResult
  • JavaScriptResult
  • ContentResult
  • FileContentResult
  • FileStreamResult
  • FilePathResult
24) Mention what is the importance of NonActionAttribute?

All public methods of a controller class are treated as the action method if you want to prevent this default method then you have to assign the public method with NonActionAttribute.

25) Mention what is the use of the default route {resource}.axd/{*pathinfo} ?

This default route prevents request for a web resource file such as Webresource.axd or ScriptResource.axd from being passed to the controller.

26) Mention the order of the filters that get executed, if the multiple filters are implemented?

The filter order would be like
  • Authorization filters
  • Action filters
  • Response filters
  • Exception filters
27) Mention what filters are executed in the end?

In the end “Exception Filters” are executed.

28) Mention what are the file extensions for razor views?

For razor views the file extensions are
  • .cshtml: If C# is the programming language
  • .vbhtml: If VB is the programming language
29) Mention what are the two ways for adding constraints to a route?

Two methods for adding constraints to route is
  • Using regular expressions
  • Using an object that implements IRouteConstraint interface
30) Mention two instances where routing is not implemented or required?

Two instance where routing is not required are
  • When a physical file is found that matches the URL pattern
  • When routing is disabled for a URL pattern
31) Mention what are main benefits of using MVC?

There are two key benefits of using MVC
  • As the code is moved behind a separate class file, you can use the code to a great extent
  • As behind code is simply moved to.NET class, it is possible to automate UI testing. This gives an opportunity to automate manual testing and write unit tests.
32). Explain MVC (Model-View-Controller) in general?

MVC (Model-View-Controller) is an architectural software pattern that basically decouples various components of a web application. By using MVC pattern, we can develop applications that are more flexible to changes without affecting the other components of our application.
  •  “Model”, is basically domain data.
  •  “View”, is user interface to render domain data.
  •  “Controller”, translates user actions into appropriate operations performed on model.
33). What is ASP.NET MVC?

ASP.NET MVC is a web development framework from Microsoft that is based on MVC (Model-View-Controller) architectural design pattern. Microsoft has streamlined the development of MVC based applications using ASP.NET MVC framework.

34). Difference between ASP.NET MVC and ASP.NET WebForms?

ASP.NET Web Forms uses Page controller pattern approach for rendering layout, whereas ASP.NET MVC uses Front controller approach. In case of Page controller approach, every page has its own controller i.e. code-behind file that processes the request. On the other hand, in ASP.NET MVC, a common controller for all pages processes the requests. Follow the link for the difference between the ASP.NET MVC and ASP.NET WebForms.

35). What are the Core features of ASP.NET MVC?

Core features of ASP.NET MVC framework are:
  • Clear separation of application concerns (Presentation and Business Logic). It reduces complexity that makes it ideal for large scale applications where multiple teams are working.
  • It’s an extensible as well as pluggable framework. We can plug components and further customize them easily.
  • It provides extensive support for URL Routing that helps to make friendly URLs (means friendly for human as well as Search Engines).
  • It supports for Test Driven Development (TDD) approach. In ASP.NET WebForms, testing support is dependent on Web Server but ASP.NET MVC makes it independent of Web Server, database or any other classes.
  • Support for existing ASP.NET features like membership and roles, authentication and authorization, provider model and caching etc.
36). Can you please explain the request flow in ASP.NET MVC framework?

Request flow for ASP.NET MVC framework is as follows: Request hits the controller coming from client. Controller plays its role and decides which model to use in order to serve the request. Further passing that model to view which then transforms the model and generate an appropriate response that is rendered to client.

37). What is Routing in ASP.NET MVC?

In case of a typical ASP.NET application, incoming requests are mapped to physical files such as .aspx file. On the other hand, ASP.NET MVC framework uses friendly URLs that more easily describe user’s action but not mapped to physical files. Let’s see below URLs for both ASP.NET and ASP.NET MVC.

//ASP.NET  approach – Pointing to physical files (Student.aspx) //Displaying all students http://locahost:XXXX/Student.aspx //Displaying a student by Id = 5 http://locahost:XXXX/Student.aspx?Id=5
//ASP.NET MVC approach – Pointing to Controller i.e. Student //Displaying all students http://locahost:XXXX/Student //Displaying student by Id = 5 http://locahost:XXXX/Student/5/

ASP.NET MVC framework uses a routing engine, that maps URLs to controller classes. We can define routing rules for the engine, so that it can map incoming request URLs to appropriate controller. Practically, when a user types a URL in a browser window for an ASP.NET MVC application and presses “go” button, routing engine uses routing rules that are defined in Global.asax file in order to parse the URL and find out the path of corresponding controller. You can find complete details of ASP.NET MVC Routing here.

38). What is the difference between ViewData, ViewBag and TempData?

In order to pass data from controller to view and in next subsequent request, ASP.NET MVC framework provides different options i.e. ViewData, ViewBag and TempData. Both ViewBag and ViewData are used to to communicate between controller and corresponding view. But this communication is only for server call, it becomes null if redirect occurs.

So, in short, its a mechanism to maintain state between controller and corresponding view. ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature). ViewData being a dictionary object is accessible using strings as keys and also requires typecasting for complex types. On the other hand, ViewBag doesn’t have typecasting and null checks. TempData is also a dictionary object that stays for the time of an HTTP Request. So, Tempdata can be used to maintain data between redirects i.e from one controller to the other controller.

39). What are Action Methods in ASP.NET MVC?

As I already explained about request flow in ASP.NET MVC framework that request coming from client hits controller first. Actually MVC application determines the corresponding controller by using routing rules defined in Global.asax. And controllers have specific methods for each user actions. Each request coming to controller is for a specific Action Method. The following code sample, “ShowBook” is an example of an Action Method.

  public ViewResult ShowBook(int id)   {            var computerBook = db.Books.Where(p => P.BookID == id).First();            return View(computerBook);   }

Action methods perform certain operation using Model and return result back to View. As in above example, ShowBook is an action method that takes an Id as input, fetch specific book data and returns back to View as ViewResult.

In ASP.NET MVC, we have many built-in ActionResults type:
  • ViewResult
  • PartialViewResult
  • RedirectResult
  • RedirectToRouteResult
  • ContentResult
  • JsonResult
  • EmptyResult
  • and many more….
Important Note: All public methods of a Controller in ASP.NET MVC framework are considered to be Action Methods by default. If we want our controller to have a Non Action Method, we need to explicitly mark it with NonAction attribute as follows:

[NonAction] public void MyNonActionMethod() { ….. }

40). Explain the role of Model in ASP.NET MVC?

One of the core feature of ASP.NET MVC is that it separates the input and UI logic from business logic. Role of Model in ASP.NET MVC is to contain all application logic including validation, business and data access logic except view i.e. input and controller i.e UI logic. Model is normally responsible for accessing data from some persistent medium like database and manipulate it, so you can expect that interviewer can ask questions on database access topics here along with ASP.NET MVC Interview Questions.

41). What are Action Filters in ASP.NET MVC?

If we need to apply some specific logic before or after action methods, we use action filters. We can apply these action filters to a controller or a specific controller action. Action filters are basically custom classes that provide a mean for adding pre-action or post-action behavior to controller actions.

For example:
  • Authorize filter can be used to restrict access to a specific user or a role.
  • OutputCache filter can cache the output of a controller action for a specific duration.
  • and more.
42). What are the new features introduced in ASP.NET MVC5?

ASP.NET MVC5 was introduced with following exciting features:
  • ASP.NET Identity
  • Authentication Filters
  • Filter Overrides
  • Scaffolding
  • Bootstrap
  • Attribute Routing
43). What is a ViewEngine in ASP.NET MVC?

“View Engine in ASP.NET MVC is used to translate our views to HTML and then render to browser.” There are few View Engines available for ASP.NET MVC but commonly used View Engines are Razor, Web Forms/ASPX, NHaml and Spark etc. Most of the developers are familiar with Web Forms View Engine (ASPX) and Razor View Engine.
  • Web Form View Engine was with ASP.NET MVC since beginning.
  • Razor View Engine was introduced later in MVC3.
  • NHaml is an open source view engine since 2007.
  • Spark is also an open source since 2008.
44). What is the difference between Razor View Engine and ASPX View Engine?

I have written a separate detailed blog post to understand the  Difference between ASPX View Engine and Razor View Engine. You can follow the link to get detailed step by step description  here. Most important differences are listed below:

ASPX View Engine

Razor View Engine

WebForms View Engine uses namespace “System.Web.Mvc.WebFormViewEngine”. “System.Web.Razor” is the namespace for Razor View Engine.
Comparatively fast. A little bit slower than ASPX View Engine.
Nothing like Test Driven Development Good support for Test Driven Development.
Syntax for ASPX View Engine is inherited from Web Forms pages as: <%= employee.FullName %> Syntax for Razor View Engine is comparatively less and clean. @employee.FullName

45). What is a ViewModel in ASP.NET MVC?

A ViewModel basically acts as a single model object for multiple domain models, facilitating to have only one optimized object for View to render. 

There are multiple scenarios where using ViewModel becomes obvious choice.

For example:
  • Parent-Child View Scenario
  • Reports where often aggregated data required
  • Model object having lookup data
  • Dashboards displaying data from multiple sources
 46). What are ASP.NET MVC HtmlHelpers?

ASP.NET MVC HtmlHelpers fulfills almost the same purpose as that of ASP.NET Web From Controls. For imlementation point of view, HtmlHelper basically is a method that returns a string ( i.e. an HTML string to render HTML tags). So, in ASP.NET MVC we have HtmlHelpers for links, Images and for Html form elements etc. as follows:

@Html.ActionLink(“WebDev Consulting Company Profile”, “CompanyInfo”) will render: <a href=”/Site/CompanyInfo”>WebDev Consulting Company Profile</a>
and
@Html.TextBox(“strEmployeeName”) renders: <input id=”strEmployeeName” name=”strEmployeeName” type=”text” value=”” />

47). What is Bootstrap in MVC5?

Bootstrap (a front-end framework) is an open source collection of tools that contains HTML and CSS-based design templates along with Javascript to create a responsive design for web applications. Bootstrap provides a base collection including layouts, base CSS, JavaScript widgets, customizable components and plugins. Project Template in ASP.NET MVC5 is now using bootstrap that enhances look and feel with easy customization.

48). Explain Attribute Routing in ASP.NET MVC5?

We already have discussed about Routing in Question#6 that in ASP.NET MVC, we use friendly URLs that are mapped to controller’s actions instead of physical files as in case of ASP.NET WebForms. Now in ASP.NET MVC5, we can use attributes to define routes giving better control over the URIs. 

49). What is Scaffolding in ASP.NET MVC? and what are the advantages of using it?

We (developers) spent most of our time writing code for CRUD operations that is connecting to a database and performing operations like Create, Retrieve, Update and Delete. Microsoft introduces a very powerful feature called Scaffolding that does the job of writing CRUD operations code for us.

Scaffolding is basically a Code Generation framework. Scaffolding Engine generates basic controllers as well as views for the models using Micrsoft’s T4 template. Scaffolding blends with Entity Framework and creates the instance for the mapped entity model and generates code of all CRUD Operations. As a result we get the basic structure for a tedious and repeatative task. You can find a detailed Web Development Tutorial with implementation on ASP.NET MVC Scaffolding here.

Following are the few advantages of Scaffolding:
  • RAD approach for data-driven web applications.
  • Minimal effort to improve the Views.
  • Data Validation based on database schema.
  • Easily created filters for foreign key or boolean fields.
50). Briefly explain ASP.NET Identity?

Microsoft introduces ASP.NET Identity as a system to manage access in ASP.NET application on premises and also in the cloud. There were issues with Membership Provider Model especially when we want to implement more advanced security features in our applications, so ASP.NET Identity gets away from the membership provider model. If we look into the history of membership, its like follows:

ASP.NET 2.0 Membership (VS 2005)
  • Forms Authentication
  • Sql Server Based Membership
ASP.NET Simple Membership (VS 2010)
  • Easy to customize profile
  • ASP.NET Web Pages
ASP.NET Universal Providers (VS2012)
  • Support Sql Azure
ASP.NET Identity is much improved system to manage access to our application and services.



Subscribe to get more Posts :