MVC Interview Questions .net - best interview questions

MVC Interview Questions - best interview questions

If you're planning to attend a .NET Interview, you may also be prepared for ASP.NET MVC interview questions. MVC is the framework used to build Web applications for .NET and C#. In this article, I list the top 50 MVC questions and their answers. The answers are code examples written by authors of C# Corner.  

1. What is MVC (Model View Controller)?

Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representation of information from the way that information is presented to or accepted from the user.

MVC is a framework for building web applications using an MVC (Model View Controller) design:

The Model represents the application core (for instance a list of database records).

The View displays the data (the database records).

The Controller handles the input (to the database records).

The MVC model also provides full control over HTML, CSS, and JavaScript.

Most Asked ASP.NET MVC Interview Questions and Answers

The MVC model defines web applications with 3 logic layers,

The business layer (Model logic)

The display layer (View logic)

The input control (Controller logic)

The Model is the part of the application that handles the logic for the application data.

Often model objects retrieve data (and store data) from a database.

The View is the part of the application that handles the display of the data.

Most often the views are created from the model data.

The Controller is the part of the application that handles user interaction.

Typically controllers read data from a view, control user input, and send input data to the model.

The MVC separation helps you manage complex applications because you can focus on one aspect a time. For example, you can focus on the view without depending on the business logic. It also makes it easier to test an application.

The MVC separation also simplifies group development. Different developers can work on the view, the controller logic, and the business logic in parallel.

Learn more about ASP.NET MVC here: Overview Of ASP.NET MVC

2. What are the advantages of MVC?

Multiple view support

Due to the separation of the model from the view, the user interface can display multiple views of the same data at the same time.

Change Accommodation

User interfaces tend to change more frequently than business rules (different colors, fonts, screen layouts, and levels of support for new devices such as cell phones or PDAs) because the model does not depend on the views, adding new types of views to the system generally does not affect the model. As a result, the scope of change is confined to the view.

SoC – Separation of Concerns

Separation of Concerns is one of the core advantages of ASP.NET MVC. The MVC framework provides a clean separation of the UI, Business Logic, Model or Data.

More Control

The ASP.NET MVC framework provides more control over HTML, JavaScript, and CSS than the traditional Web Forms.

Testability

ASP.NET MVC framework provides better testability of the Web Application and good support for test driven development too.

Lightweight

ASP.NET MVC framework doesn’t use View State and thus reduces the bandwidth of the requests to an extent.

Full features of ASP.NET

One of the key advantages of using ASP.NET MVC is that it is built on top of the ASP.NET framework and hence most of the features of the ASP.NET like membership providers, roles, etc can still be used.

Most Asked ASP.NET MVC Interview Questions and Answers

Here is a detailed article on Creating a Simple Application Using MVC 4.0.

3. Explain MVC application life cycle?

Any web application has two main execution steps, first understanding the request and depending on the type of the request sending out an appropriate response. 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. The following 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 rout table with routes collection. This filling of the route table happens the global.asax file

Step 2 - Fetch route

Depending on the URL sent “UrlRoutingModule” searches the route table to create “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 “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 a Response object

This phase has two steps executing the action and finally sending the response as a result to the view.

Most Asked ASP.NET MVC Interview Questions and Answers

Here is a complete article on ASP.Net MVC Life Cycle.

4. List out different return types of a controller action method?

There are total of nine return types we can use to return results from the controller to view.

The base type of all these result types is ActionResult.

ViewResult (View)

This return type is used to return a webpage from an action method.

PartialviewResult (Partialview)

This return type is used to send a part of a view that will be rendered in another view.

RedirectResult (Redirect)

This return type is used to redirect to any other controller and action method depending on the URL.

RedirectToRouteResult (RedirectToAction, RedirectToRoute)

This return type is used when we want to redirect to any other action method.

ContentResult (Content)

This return type is used to return HTTP content type like text/plain as the result of the action.

jsonResult (json)

This return type is used when we want to return a JSON message.

javascriptResult (javascript)

This return type is used to return JavaScript code that will run in the browser.

FileResult (File)

This return type is used to send binary output in response.

EmptyResult

This return type is used to return nothing (void) in the result.

Here is a complete article on Various Return Types From MVC Controller.

5. What are the Filters in MVC?

In MVC, controllers define action methods and these action methods generally have a one-to-one relationship with UI controls such as clicking a button or a link, etc. For example, in one of our previous examples, the UserController class contained methods UserAdd, UserDelete, etc.

But many times we would like to perform some action before or after a particular operation. For achieving this functionality, ASP.NET MVC provides a feature to add pre and post-action behaviors on the controller's action methods.

Types of Filters

ASP.NET MVC framework supports the following action filters,

Action Filters

Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter.

Authorization Filters

Authorization filters are used to implement authentication and authorization for controller actions.

Result Filters

Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.

Exception Filters

Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You can also use exception filters to log errors.

Action filters are one of the most commonly used filters to perform additional data processing, or manipulating the return values or canceling the execution of an action or modifying the view structure at run time.

Here is a complete article on Understanding Filters in MVC.

6. What are Action Filters in MVC?

Answer - Action Filters

Action Filters are additional attributes that can be applied to either a controller section or the entire controller to modify the way in which action is executed. These attributes are special .NET classes derived from System.Attribute which can be attached to classes, methods, properties, and fields.

ASP.NET MVC provides the following action filters,

Output Cache

This action filter caches the output of a controller action for a specified amount of time.

Handle Error

This action filter handles errors raised when a controller action executes.

Authorize

This action filter enables you to restrict access to a particular user or role.

Now we will see the code example to apply these filters on an example controller ActionFilterDemoController. (ActionFilterDemoController is just used as an example. You can use these filters on any of your controllers.)

Output Cache

Code Example

Specifies the return value to be cached for 10 seconds.

public class ActionFilterDemoController: Controller

{

    [HttpGet]

    OutputCache(Duration = 10)]

    public string Index()

    {

        return DateTime.Now.ToString("T");

    }

}

C#

Learn more here: ASP.NET MVC with Action Filters

7. Explain what is routing in MVC? What are the three segments for routing important?

Routing is a mechanism to process the incoming URL that is more descriptive and gives the desired response. In this case, URL is not mapped to specific files or folder as was the case of earlier days web sites.

There are two types of routing (after the introduction of ASP.NET MVC 5).

Convention-based routing - to define this type of routing, we call MapRoute method and set its unique name, URL pattern and specify some default values.

Attribute-based routing - to define this type of routing, we specify the Route attribute in the action method of the controller.

Routing is the URL pattern that is mapped together to a handler,routing is responsible for incoming browser request for particular MVC controller. In other ways let us say routing help you to define a URL structure and map the URL with controller. There are three segments for routing that are important,

ControllerName

ActionMethodName

Parammeter

Code Example

ControllerName/ActionMethodName/{ParamerName} and also route map coding written in a Global.asax file.

Learn more here - Routing in MVC.

8. What is Route in MVC? What is Default Route in MVC?

A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as a .aspx file in a Web Forms application. A handler can also be a class that processes the request, such as a controller in an MVC application. To define a route, you create an instance of the Route class by specifying the URL pattern, the handler, and optionally a name for the route.

You add the route to the application by adding the Route object to the static Routes property of the RouteTable class. The Routesproperty is a RouteCollection object that stores all the routes for the application.

You typically do not have to write code to add routes in an MVC application. Visual Studio project templates for MVC include preconfigured URL routes. These are defined in the MVC Application class, which is defined in the Global.asax file.

Route definition    Example of matching URL

{controller}/{action}/{id}  /Products/show/beverages

{table}/Details.aspx    /Products/Details.aspx

blog/{action}/{entry}   /blog/show/123

{reporttype}/{year}/{month}/{day}   /sales/2008/1/5

{locale}/{action}   /US/show

{language}-{country}/{action}   /en-US/show

Default Route

The default ASP.NET MVC project templates add a generic route that uses the following URL convention to break the URL for a given request into three named segments.

URL: "{controller}/{action}/{id}"

This route pattern is registered via a call to the MapRoute() extension method of RouteCollection.

Most Asked ASP.NET MVC Interview Questions and Answers

9. Mention what is the difference between Temp data, View, and View Bag?

In ASP.NET MVC there are three ways to pass/store data between the controllers and views.

ViewData

ViewData is used to pass data from controller to view.

It is derived from ViewDataDictionary class.

It is available for the current request only.

Requires typecasting for complex data types and checks for null values to avoid an error.

If redirection occurs, then its value becomes null.

ViewBag


ViewBag is also used to pass data from the controller to the respective view.

ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0

It is also available for the current request only.

If redirection occurs, then its value becomes null.

It doesn’t require typecasting for the complex data type.

TempData

TempData is derived from TempDataDictionary class

TempData is used to pass data from the current request to the next request

It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action

It requires typecasting for complex data types and checks for null values to avoid an error. Generally, it is used to store only one time messages like the error messages and validation messages

Learn more here: Difference Between ViewData, ViewBag, and TempData

10. What is Partial View in MVC?

A partial view is a chunk of HTML that can be safely inserted into an existing DOM. Most commonly, partial views are used to componentize Razor views and make them easier to build and update. Partial views can also be returned directly from controller methods. In this case, the browser still receives text/html content but not necessarily HTML content that makes up an entire page. As a result, if a URL that returns a partial view is directly invoked from the address bar of a browser, an incomplete page may be displayed. This may be something like a page that misses title, script and style sheets. However, when the same URL is invoked via a script, and the response is used to insert HTML within the existing DOM, then the net effect for the end-user may be much better and nicer.

Post a Comment

Previous Post Next Post