Loading, please wait...

A to Z Full Forms and Acronyms

Top 40 Most Asked Asp.net MVC Interview Questions and Answers

Here in this article I will explain top 40 most asked Asp.net MVC interview questions and answers

Are you preparing for the next job interviews in Microsoft ASP.NET MVC? If yes, trust me this post will help you also we'll suggest you check out a big collection for Programming Full Forms that may help you in your interview:

List of Programming Full Forms 

ASP.NET MVC Interview Questions and Answer

Q1. What is MVC (Model View Controller)?

MVC is a software architecture pattern for developing web application. It is handled by three objects Model-View-Controller. Below is how each one of them handles the task.

  • The View is responsible for the look and feel.
  • The model represents the real-world object and provides data to the View.
  • The Controller is responsible for taking the end-user request and loading the appropriate Model and View

Q2. What is 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 the 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. Below is a detailed explanation.

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 route table with routes collection. This filling of the route table happens in the global.asax file. 

Step 2 Fetch route:  Depending on the URL sent “UrlRoutingModule” searches the route table to create the “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 the “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.

Step 5 Creating Response object:  This phase has two steps executing the action and finally sending the response as a result to the view.

 

Q3. Explain in which assembly is the MVC framework is defined?

The MVC framework is defined in System.Web.MVC assembly, which you can directly use from Nuget or from scaffolding templates of Visual Studio.

Q4. What are the advantages of MVC?

ASP.NET have many advantages and some of them are listed below:

  • A main advantage of MVC is the separation of concern. Separation of concern means we divide the application Model, Control and View.
  • We can easily maintain our application because of the separation of concern.
  • At the same time, we can split many developers work at a time. It will not affects one developer work to another developer work.
  • It supports TTD (test-driven development). We can create an application with a unit test. We can write a won test case.
  • The latest version of MVC Support default responsive web site and mobile templates.

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

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

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

Q6. What is the difference between each version of MVC 2, 3, 4, 5 and 6?

In ASP .NET MVC 6 

  • ASP.NET MVC and Web API have been merged into one.
  • Side by side - deploy the runtime and framework with your application
  • No need to recompile for every change. Just hit save and refresh the browser.
  • Dependency injection is inbuilt and part of MVC.
  • Everything packaged with NuGet, Including the .NET runtime itself.
  • New JSON based project structure.
  • The compilation is done with the new Roslyn real-time compiler.

In ASP.NET MVC 5

  • Asp.Net Identity
  • Attribute-based routing
  • Bootstrap in the MVC template
  • Filter overrides
  • Authentication Filters

In ASP.NET MVC 4

  • ASP.NET Web API
  • New mobile project template
  • Refreshed and modernized default project templates
  • Many new features to support mobile apps

In ASP.NET MVC 3

  • Razor
  • HTML 5 enabled templates
  • JavaScript and Ajax
  • Support for Multiple View Engines
  • Model Validation Improvements

In ASP.NET MVC 2

  • Templated Helpers
  • Client-Side Validation
  • Areas
  • Asynchronous Controllers
  • Html.ValidationSummary Helper Method
  • DefaultValueAttribute in Action-Method Parameters
  • Binding Binary Data with Model Binders
  • DataAnnotations Attributes
  • Model-Validator Providers
  • New RequireHttpsAttribute Action Filter

Q7. What are Filters in MVC?

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

Types of ASP.NET MVC 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.
  • 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: 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.

Q8. What are Action Filters in MVC?

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 Filter:

E.g.: Specifies the return value to be cached for 10 seconds.

publicclassActionFilterDemoController: Controller 
{ 
    [HttpGet] 
    [OutputCache(Duration = 10)] 
    publicstringIndex() 
    { 
       returnDateTime.Now.ToString("T"); 
    } 

} 

Q9. What are HTML helpers in MVC?

HTML helpers help you to render HTML controls in the view. For instance, if you want to display an HTML textbox on the view, below is the HTML helper code.

<%= Html.TextBox("FirstName") %>

For the checkbox below is the HTML helper code. In this way, we have HTML helper methods for every HTML control that exists.

<%= Html.CheckBox("Yes") %>

Q 10. What is the difference between “HTML.TextBox” and “HTML.TextBoxFor”?

Both provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t.     Below is a simple HTML code which just creates a simple textbox with “FirstName” as name.

Html.TextBox("FirstName ")

Below is “Html.TextBoxFor” code which creates HTML textbox using the property name ‘FirstName” from object “m”.

Html.TextBoxFor(m => m.CustomerCode)

In the same way, we have other HTML controls like for checkbox we have “Html.CheckBox” and “Html.CheckBoxFor”.

Q 11. What is Route in MVC and also the 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 in ASP.NET MVC:

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. 

Q 12. Where is the route mapping code written in ASP.NET MVC?

The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax" application start event.

Q 13. 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 in ASP.NET MVC

  • 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 type and checks for null values to avoid an error.
  • If redirection occurs, then its value becomes null.

ViewBag in ASP.NET MVC

  • 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.
  • Doesn’t require typecasting for the complex data type.

TempData in ASP.NET MVC

  • 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 type 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

Q 14. What is Partial View in ASP.NET MVC?

A partial view is a reusable view (like a user control) that can be embedded inside another view, like a user control on our classical ASP.NET WebForms.

For example, let’s say all your pages of your site have a standard structure with a left menu, header, and footer as shown in the image below.

For every page, you would like to reuse the left menu, header, and footer controls. So you can go and create partial views for each of these items and then you call that partial view in the main view.

Q 15. How did you create a partial view and use it?

When you add a view to your project you need to check the “Create partial view” check box.

 How did you create a partial view and use it?

Figure: Create a partial view

Once the partial view is created you can then call the partial view in the main view using the Html.RenderPartial method as shown in the below code snippet:

<body>
     <div>
         <% Html.RenderPartial("MyView"); %>
     </div>
</body>

Q 16. Explain what is the difference between View and Partial View?

There are many differences between ASP.NET Views and ASP.NET Partial Views, here below we'll learn about them in details:

ASP.NET View Vs Partial Views

ASP.NET View:

  • It contains the layout page.
  • Before any view is rendered, the view start page is rendered.
  • The view might have markup tags like body, HTML, head, title, meta etc.
  • The view is not lightweight as compare to Partial View.

ASP.NET 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 of any markup.
  • We can pass a regular view to the RenderPartial method.

Q17. Explain attribute-based routing in MVC?

In ASP.NET MVC 5.0 we have a new attribute route, By using the "Route" attribute we can define the URL structure. For example, in the below code we have decorated the "GotoAbout" action with the route attribute. The route attribute says that the "GotoAbout" can be invoked using the URL structure "Users/about".

public class HomeController: Controller 
{ 

    [Route("Users/about")] 
    publicActionResultGotoAbout() 
    { 
        return View(); 
    } 

} 

Q18. What is Razor in ASP.NET MVC?

Razor is not a new programming language itself, but uses C# syntax for embedding code in a page without the ASP.NET delimiters: <%= %>. It is a simple syntax view engine and was released as part of ASP.NET MVC 3. The Razor file extension is "cshtml" for the C# language. It supports TDD (Test Driven Development) because it does not depend on the "System.Web.UI.Page class".

Q19. How to implement Forms authentication in MVC?

ASP.NET forms authentication occurs after IIS authentication is completed. You can configure forms authentication by using the forms element within the "web.config" file of your application. The default attribute values for forms authentication are shown below:

<system.web> 
    <authenticationmode="Forms"> 
        <formsloginUrl="Login.aspx" protection="All" timeout="30" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="default.aspx" cookieless="UseDeviceProfile" enableCrossAppRedirects="false" /> 
        </authentication> 
</system.web> 

The FormsAuthentication class creates the authentication cookie automatically when SetAuthCookie() or RedirectFromLoginPage() methods are called. The value of the authentication cookie contains a string representation of the encrypted and signed FormsAuthenticationTicket object.

Q 20. What are Areas in ASP.NET MVC?

From ASP.Net MVC 2.0 Microsoft provided a new feature in MVC applications, Areas. Areas are just a way to divide or “isolate” the modules of large applications in multiple or separated MVC. like:

When you add an area to a project, a route for the area is defined in an AreaRegistration file. The route sends requests to the area based on the request URL. To register routes for areas, you add code to the "Global.asax" file that can automatically find the area routes in the AreaRegistration file.

Q21. Explain, What is ASP.NET MVC Scaffolding?

ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Visual Studio 2013 includes pre-installed code generators for MVC and Web API projects. You add scaffolding to your project when you want to quickly add code that interacts with data models. Using scaffolding can reduce the amount of time to develop standard data operations in your project.

Scaffolding consists of page templates, entity page templates, field page templates, and filter templates. These templates are called Scaffold templates and allow you to quickly build a functional data-driven Website.