Tuesday 1 January 2019

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

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

  1. 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 the detail 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 route table happens in 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.
Step 5 Creating Response object:  This phase has two steps executing the action and finally sending the response as a result to the view.
 

  1. Explain in which assembly is the MVC framework is defined?
The MVC framework is defined in System.Web.Mvc.

  1. What are the advantages of MVC
  • A main advantage of MVC is separation of concern. Separation of concern means we divide the application Model, Control and View.
  • We can easily maintain our application because of separation of concern.
  • In 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 unit test. We can write won test case.
  • Latest version of MVC Support default responsive web site and mobile templates.
 


  1. List out different return types of a controller action method?
There are total nine return types we can use to return results from 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 which 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 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.

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

MVC 6 
ASP.NET MVC and Web API has been merged in to 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.
Compilation done with the new Roslyn real-time compiler.

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

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

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

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


  1. 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 feature to add pre and post action behaviors on 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.
  • 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.

  1. 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
E.g.: Specifies the return value to be cached for 10 seconds.
publicclassActionFilterDemoController: Controller 

{ 

    [HttpGet] 

    OutputCache(Duration = 10)] 

publicstringIndex() 

{ 

    returnDateTime.Now.ToString("T"); 

} 

} 

 


  1. What are HTML helpers in MVC?
HTML helpers help you to render HTML controls in the view. For instance if you want to display a HTML textbox on the view , below is the HTML helper code.
<%= Html.TextBox("FirstName") %>

For checkbox below is the HTML helper code. In this way we have HTML helper methods for every HTML control that exists.
<%= Html.CheckBox("Yes") %>

  1. 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 for other HTML controls like for checkbox we have “Html.CheckBox” and “Html.CheckBoxFor”.

  1. 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 call to the MapRoute() extension method of RouteCollection.
       

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

  1. 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 type and checks for null values to avoid 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.
  • Doesn’t require typecasting for 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 type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages


  1. What is Partial View in MVC?
 Partial view is a reusable view (like a user control) which can be embedded inside other view. For example let’s say all your pages of your site have a standard structure with 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.

  1. How did you create a partial view and consume it?
When you add a view to your project you need to check the “Create partial view” check box.

 
Figure: Create 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>

  1. Explain what is the difference between View and Partial View?

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.


No comments:

Post a Comment