;

Most Asked ASP.NET MVC Interview Questions


Tutorialsrack 20/02/2019 ASP.NET MVC

The ASP.NET MVC framework is one of the most popular frameworks for developing web applications. If you have been working in .NET and developing web-based applications, then there is a good chance that you have already used ASP.NET MVC in your projects. There is a high demand for good ASP.NET MVC developers with knowledge and experience in .NET and ASP.NET MVC. One way to prepare yourself for such job interviews is to look for potential interview questions. These are some MVC interview questions I have faced during MVC interviews:-

Q1. What is MVC? Explain briefly.

Answer:   MVC Stands For Model, View, Controller.MVC is an architectural pattern that separates an application into three Interconnected parts: Model, View, and Controller.
Model: It is used to represent application data.
View:  It is used to represent user interface
Controller:  It is used to handle the request sent by the user's and return an output response according to the user's requests through View.

Q2. Do you know about the new features in ASP.NET MVC 4?

Answer:  Following are features added newly:-

  • Includes ASP.NET Web API, a new framework for creating Rest based services.
  • Includes Mobile Templates.
  • Includes Task Support for Asynchronous Controllers.
  • Includes Bundling of javascript.
  • Includes Enabling Logins from Facebook and Other Sites Using OAuth and OpenID.The default templates in ASP.NET MVC 4 Internet Project template now includes support for OAuth and OpenID login using the DotNetOpenAuth library.

Q3. Can you explain the page life cycle of ASP.NET MVC?

AnswerBelow is the process followed in the sequence:

  • App initialization
  • Routing
  • Instantiate and execute controller
  • Locate and invoke controller action
  • Instantiate and render view

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

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

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

Answer: There are 9 return types we can use to return results from a controller to view as given below:-

  1. ViewResult (View): This return type is used to return a webpage from an action method.
  2. PartialviewResult (Partialview): This return type is used to send a part of a view that will be rendered in another view.
  3. RedirectResult (Redirect): This return type is used to redirect to any other controller and action method depending on the URL.
  4. RedirectToRouteResult (RedirectToAction, RedirectToRoute): This return type is used when we want to redirect to any other action method.
  5. ContentResult (Content): This return type is used to return HTTP content type like text/plain as the result of the action.
  6. jsonResult (json): This return type is used when we want to return a JSON message.
  7. javascriptResult (javascript): This return type is used to return JavaScript code that will run in the browser.
  8. FileResult (File): This return type is used to send binary output in response.
  9. EmptyResult: This return type is used to return nothing (void) in the result.

Q6. What are the Filters in ASP.NET MVC?

Answer: In ASP.NET MVC, many times we would like to perform some actions before or after the action method gets executed. For achieving this functionality,ASP.NET MVC provides a feature to add pre or post-action behavior on the controllers action method.

Q7. What are the different types of Filter in ASP.NET MVC?

Answer: ASP.NET MVC framework supports the following action filters:

  • Authorization Filters: Authorization filters are used to implement authentication and authorization for controller actions.
  • 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.
  • 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.

Q8. What are Action Filters in ASP.NET MVC?

Answer: An action filter is an attribute that you can apply to a controller action or an entire controller that modifies the way in which the action is executed. These attributes are special .NET classes derived from System. An attribute that can be attached to classes, methods, properties, and fields. The ASP.NET MVC framework includes several 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.

Q9. What are HTML helpers in ASP.NET MVC?

Answer: In ASP.NET MVC, HTML helpers are much like traditional ASP.NET Web Form controls. Just like web form controls in ASP.NET, HTML helpers are used to modifying HTML. But HTML helpers are more lightweight. Unlike Web Form controls, an HTML helper does not have an event model and a view state.

In Short, HTML helpers help you to render HTML controls in the view Programmatically. For Example, if you want to display an HTML textbox on the view, below is the HTML Helper code

Example
@Html.TextBox("txt_Name")

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

Example
@Html.CheckBox("Yes")

Q11. What is Bundling and Minification in ASP.NET MVC?

Answer:

Bundling: Bundling is a new feature in ASP.NET 4.5 that makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript, and other bundles. Fewer files mean fewer HTTP requests and that can improve first-page load performance.

Minification: Minification performs a variety of different code optimizations to scripts or CSS, such as removing unnecessary white space and comments and shortening variable names to one character.

Q12. What is routing in ASP.NET MVC?

Answer: In ASP.NET MVC, Routing is a pattern matching mechanism that is responsible for mapping incoming browser request to particular MVC controller action method.

Q13. Where is the route mapping code written?

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

Q14. Can we map multiple URLs to the same action?

Answer: Yes, you can, you just need to make two entries with different key names and specify the same controller and action.

Q15. Explain attribute-based routing in ASP.NET  MVC?

Answer: Attribute-based Routing is yet another new feature in MVC 5, in this feature you can apply route attribute on Controller and Action such that it influences the selection of Controller and Action Method.

Attribute-based Routing is totally different from traditional routing in traditional routing we declare route in RouteConfig.cs file.

Example
public class HomeController : Controller
{
// eg: /home
[Route(“home”)]
public ActionResult Index() { … }
// eg: /article/5
[Route(“article/{PostId}”)]
public ActionResult Show(int PostId) { … }
// eg: /article/5/edit
[Route(“article/{PostId}/edit”)]
public ActionResult Edit(int PostId) { … }
}

Q16. How to enable attribute routing in ASP.NET MVC?

Answer: To enable attribute routing, call MapMvcAttributeRoutes during configuration.

Example
public class RouteConfig
{
     public static void RegisterRoutes(RouteCollection routes)
     {
        routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);

        routes.MapMvcAttributeRoutes();
     }
}

Q17. Which are the important Namespaces used in ASP.NET MVC?

Answer: Below are the important namespaces used in ASP.NET MVC :

  • System.Web.ASP.Net MVC
  • System.Web.ASP.Net MVC.Ajax
  • System.Web.ASP.Net MVC.Html
  • System.Web.ASP.Net MVC.Async

Q18. What is the difference between Viewbag And Viewdata In ASP.NET MVC?

Answer:

ViewBag:

  1. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  2. ViewBag doesn’t require typecasting for a complex data type.
Example
public ActionResult Index()
{
ViewBag.Name = "TutorialsRack.com";
return View();
}

ViewData:

  1. ViewData is a dictionary of objects that are derived from ViewDataDictionary class and is accessible using strings as keys.
  2. ViewData requires typecasting for complex data type and check for null values to avoid error.
Example
public ActionResult Index()
{
ViewData["Name"] = "TutorialsRack.com";
return View();
}

In View

Example
@ViewBag.Name 
@ViewData["Name"]

 

Q19. What is TempData in ASP.NET MVC?

Answer: TempData is a dictionary which is derived from the TempDataDictionary class. TempData can be used to store temporary data which can be used in the subsequent request. TempData will be cleared out after the completion of a subsequent request. 
In Other Words, TempData is used to passing data from one controller to another controller or one action to other action. TempData internally uses Session variables. TempData is used to pass data from one request to the next request.

Q20. How can we maintain sessions in ASP.NET MVC?

Answer: 3 different ways to deal with session management in ASP.NET MVC:-
TempData, ViewBag, and ViewData.

Q21. What is partial view in ASP.NET MVC?

Answer: In ASP.NET MVC, a partial view is similar to user control in ASP.NET Web form. Partial view is a reusable view, which can be used as a child view in multiple other views OR you can say, a partial view is a chunk of HTML that can be safely inserted into an existing View. It eliminates duplicate coding by reusing the same partial view in multiple places. You can use the partial view in the layout view, as well as other content views.

Q22. What is Layout in ASP.Net MVC?

Answer: Layout pages are similar to master pages in traditional ASP.NET Web Forms. This is used to set the common look across multiple pages. In each child page we can find :

@{
Layout = "~/Views/Shared/_Layout.cshtml";
}


This indicates child page uses TestLayout page as it's a master page.

Q23. Explain Sections is ASP.Net MVC?

Answer: Section is the part of HTML which is to be rendered in the layout page. In Layout page we will use the below syntax for rendering the HTML :

Example
@RenderSection("TestSection")

And in child pages we are defining these sections as shown below :

Example
@section TestSection{
  Test Content
}

If any child page does not have this section defined then an error will be thrown so to avoid that we can render the HTML like this :

Example
@RenderSection("TestSection", required: false)

Q24. Can you explain Renderbody() And Renderpage() in ASP.NET MVC?

Answer: Renderbody: In ASP.NET MVC, RenderBody method is very similar to ContentPlaceholder in ASP.NET WebForm. It Resides in the Layout page(or you can say Master page). There can only be one RenderBody method per Layout page.

Example
@RenderBody()

RenderPage:- RenderPage method also exists in the Layout page to render another page exists in your application. A layout page can have multiple RenderPage methods.

Example
@RenderPage("~/Views/Shared/_Header.cshtml")

Q25. What is Viewstart Page in ASP.NET MVC?

Answer: This page is used to make sure the common layout page will be used for multiple views. Code written in this file will be executed first when the application is being loaded.

Q26. How to change the action name in ASP.NET MVC?

Answer: "ActionName" attribute can be used for changing the action name.

Example
[ActionName("TestActionNew")]
public ActionResult TestAction()
{
    return View();
}

So in the above code snippet "TestAction" is the original action name and in "ActionName" attribute, name - "TestActionNew" is given. So the caller of this action method will use the name "TestActionNew" to call this action.

Q27. What are code blocks in Views?

Answer: Unlike code expressions that are evaluated and sent to the response, it is the blocks of code that are executed. This is useful for declaring variables which we may be required to be used later.

Example
@{

int x = 12000;

string y = "John Doe";

}

Q28. Can a View be shared across multiple controllers? If yes, how we can do that?

Answer: Yes, we can share a view across multiple controllers. We can put the view in the "Shared" folder. When we create a new ASP.Net MVC Project we can see the Layout page will be added in the shared folder, which is because it is used by multiple child pages.

Q29. What are the components required to create a route in ASP.NET MVC?

Answer: Name: This is the name of the route.

URL Pattern: Placeholders will be given to match the request URL pattern.

Defaults: When loading the application which controller, action to be loaded along with the parameter.

Example
public static void RegisterRoutes(RouteCollection routes)
{
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            )
}

Q30. Why use "{resource}.axd/{*pathinfo}" in routing in ASP.NET MVC?

Answer: Using this default route - {resource}.axd/{*pathInfo}, we can prevent the requests for the web resources files like - WebResource.axd or ScriptResource.axd from passing to a controller.

Q31. What are the main Razor syntax rules?

Answer: Following are the rules for main Razor Syntax:

  • Razor code blocks are enclosed in @{ … }
  • Inline expressions (variables and functions) start with @
  • Code statements end with a semicolon
  • Variables are declared with the var keyword
  • Strings are enclosed with quotation marks
  • C# code is case sensitive
  • C# files have the extension .cshtml

Q32. What are the benefits of Area in ASP.NET MVC?

Answer:  Benefits of Area in ASP.NET MVC:

  • Allows us to organize models, views, and controllers into separate functional sections of the application, such as administration, billing, customer support and much more.
  • Easy to integrate with other Areas created by another.
  • Easy for unit testing.

Q33. Can i use Razor Code in javascript in ASP.NET MVC?

Answer: Yes. We can use the razor code in javascript in cshtml by using element.

Example
<script type="text/javascript">

@foreach (var item in Model) {

<text>

//javascript goes here which uses the server values

<text>

}

</script>

Q34. How can I return string result from an action in ASP.NET MVC?

Answer: Below is the code snippet to return a string from an action method :

Example
public ActionResult TestAction() {

   return Content("Hello Test !!");

}

Q35. How to return the JSON from an action method in ASP.NET MVC?

Answer: Below is the code snippet to return a string from action method :

Example
public ActionResult TestAction() {

return JSON(new { prop1 = "Test1", prop2 = "Test2" });

}

Q36. What are Ajax Helpers in ASP.NET MVC?

Answer: AJAX Helpers are used to creating AJAX-enabled elements like as Ajax-enabled forms and links which performs the request asynchronously and these are extension methods of AJAXHelper class which exists in the namespace - System.Web.ASP.Net MVC.

Q37. What are the options can be configured in Ajax Helpers?

Answer: Below is the options in AJAX helpers :

  • Ur : This is the request URL.
  • Confirm: This is used to specify the message which is to be displayed in the confirm box.
  • OnBegin: Javascript method name to be given here and this will be called before the AJAX request.
  • OnComplete: Javascript method name to be given here and this will be called at the end of AJAX request.
  • OnSuccess:  Javascript method name to be given here and this will be called when AJAX request is successful.
  • OnFailure:  Javascript method name to be given here and this will be called when AJAX request is failed.
  • UpdateTargetId : Target element which is populated from the action returning HTML.

Q38. Explain Bundle.config In ASP.NET MVC?

Answer: "BundleConfig.cs" in ASP.Net MVC4 is used to register the bundles by the bundling and minification system. Many bundles are added by default including jQuery libraries like - jquery.validate,  Modernizr, and default CSS references.

Q39. What is the use of ViewModel in ASP.NET MVC?

Answer: View Model is a plain class with properties, which is used to bind it to strongly typed view. View Model can have the validation rules defined for its properties using data annotations.

Q40. Explain using hyperlink how you can navigate from one view to another view?

Answer: By using "ActionLink" method as shown in the below code. The below code will make a simple URL which helps to navigate to the "Home" controller and invoke the "GotoHome" action.

Example
@Html.ActionLink("Home", "Gotohome")

Q41. Mention what is the importance of NonAction Attribute?

Answer: If you decorated action method with [NonAction] attribute you can't access that through URL. We can restrict this by using private also, but in some scenarios, we need public access so by declaringing with [NonAction] attribute we can prevent.

Q42. Mention what are the file extensions for razor views?

Answer: For razor views, the file extensions are

.cshtml: If C# is the programming language
.vbhtml: If VB is the programming language

Q43. Mention what are the two ways for adding constraints to a route?

Answer: Two methods for adding constraints to the route is

  • Using regular expressions
  • Using an object that implements IRouteConstraint interface

Q44. Why Razor when we already have ASPX?

Answer: Razor is clean, lightweight, and syntaxes are easy as compared to ASPX.

Example - in ASPX to display simple time, we need to write:
<%=DateTime.Now%>

In Razor, it’s just one line of code:

Example - in Razor to display simple time, we need to write:
@DateTime.Now

Q45. So which is a better fit, Razor or ASPX?

Answer: As per Microsoft, Razor is more preferred because it’s lightweight and has simple syntaxes.

Q46. How to implement Windows authentication for MVC?

Answer: For Windows authentication, you need to modify the web.config file and set the authentication mode to Windows.

Example
<authentication mode="Windows" /> 
<authorization>
   <deny users="?" />
</authorization>
   

Then in the controller or on the action, you can use the Authorize attribute which specifies which users have access to these controllers and actions. Below is the code snippet for that. Now only the users specified in the controller and action can access it.

Example
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
    //
   // GET: /Start/
   [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
   public ActionResult Index()
   {
    return View("MyView");
   }
}

Q47. What is the difference between ActionResult and ViewResult?

Answer:

  • ActionResult is an abstract class while ViewResult derives from the ActionResult class. ActionResult has several derived classes like ViewResult, JsonResult, FileStreamResult, and so on.
  • ActionResult can be used to exploit polymorphism and dynamism. So if you are returning different types of views dynamically, ActionResult is the best thing. For example in the below code snippet, you can see we have a simple action called DynamicView. Depending on the flag (IsHtmlView) it will either return a ViewResult or JsonResult.
Example
public ActionResult DynamicView()
{
    if (IsHtmlView)
       return View(); // returns simple ViewResult
    else
       return Json(); // returns JsonResult view
}

Q48. If we have multiple filters, what’s the sequence for execution?

Answer:

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

Q49. How can we detect that an MVC controller is called by POST or GET?

Answer: To detect if the call on the controller is a POST action or a GET action we can use the Request.HttpMethod property as shown in the below code snippet.

Example
public ActionResult SomeAction()
{
    if (Request.HttpMethod == "POST")
    {
       return View("SomePage");
    }
    else
    {
       return View("SomeOtherPage");
    }
}

Q50. How can you test bundling in debug mode?

Answer: If you are in a debug mode you need to set EnableOptimizations to true in the bundleconfig.cs file or else you will not see the bundling effect in the page requests.

Example
BundleTable.EnableOptimizations = true;

Q51. What are the advantages of using ASP.NET MVC?

Answer: There are several benefits of using ASP.NET MVC are given below:

  • Separation of Concerns: Separation of Concern 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. On the other hand, we can say it provides Separation of Program logic from the User Interface.
  • More Control: The ASP.NET MVC framework provides more control over the 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 the 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 ASP.NET framework and hence most of the features of the ASP.NET like membership providers, roles etc can still be used.

Q52. Why we use ASP.NET MVC over ASP.NET Web form?

Answer: The main advantages of ASP.NET MVC are:

  • Enables the full control over the rendered HTML.
  • Provides clean separation of concerns(SoC).
  • Enables Test Driven Development (TDD).
  • Easy integration with JavaScript frameworks.
  • Following the design of the stateless nature of the web.
  • RESTful URLs that enable SEO.
  • No ViewState and PostBack events

Q53. What is the difference between "HTML.TextBox" vs "HTML.TextBoxFor"?

Answer: Both of them 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 "CustomerCode" as a name.

Example
@Html.TextBox("CustomerCode")

Below is "Html.TextBoxFor" code which creates HTML textbox using the property name "CustomerCode" from object "m".

Example
@Html.TextBoxFor(m => m.CustomerCode)

Q54. What is the use of Keep and Peek in TempData in ASP.NET MVC?

Answer: TempData is used to preserve the data for the next request, i.e. Once the data is read by the view it's lost, and not available for the next subsequent request. The data can be retained & preserved for the next subsequent request by using Keep() and Peek(), even if its read by a view.

And the main difference between keep() and peek is:

Keep: If we read “TempData” in the current request and we can keep method to persist TempData for the next request. In MVC, we are having void keep() and void keep(string key) methods to persist the data.

Example
@TempData["key"]; 
TempData.Keep("key");

Peek: If you set a TempData in your action method and if you read it in your view by calling the "Peek" method then TempData will be persisted and will be available in next request

Example
string msg = TempData.Peek("msg").ToString();

Q55. What does scaffolding use internally to connect to the database?

Answer: It uses Entity framework internally.

Q56. Explain Areas in ASP.NET MVC?

Answer: In 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. 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.

Example
protected void Application_Start()
{

    AreaRegistration.RegisterAllAreas();

}

Q58. Explain the concept of Scaffolding in ASP.NET MVC?

Answer: Scaffolding is a technique used by ASP.NET MVC frameworks( and many other MVC Frameworks like ASP.NET MVC, Ruby on Rails, Cake PHP and Node.JS etc.,) to generate code for basic CRUD (create, read, update, and delete) operations against your database effectively.

Q59. What is Output Caching in ASP.NET MVC?

Answer: The main purpose of using Output Caching is to dramatically improve the performance of an ASP.NET MVC Application. It enables us to cache the content returned by any controller method so that the same content does not need to be generated each time the same controller method is invoked. Output Caching has huge advantages, such as it reduces server round trips, reduces database server round trips, reduces network traffic etc.

Q60. What are the benefits of Area in ASP.NET MVC?

Answer: Benefits of Area in MVC:

  • Allows us to organize models, views, and controllers into separate functional sections of the application, such as administration, billing, customer support and much more.
  • Easy to integrate with other Areas created by another.
  • Easy for unit testing.

Q61. What are child actions in ASP.NET MVC?

Answer: To create reusable widgets child actions are used and this will be embedded into the parent views. In ASP.Net MVC Partial views are used to have reusability in the application. Child action mainly returns partial views.

Q62. How we can invoke Child Actions in ASP.NET MVC?

Answer: "ChildActionOnly" attribute is decorated over action methods to indicate that action method is a child action. Below is the code snippet used to denote the child action :

Example
[ChildActionOnly]
public ActionResult MenuBar()
{

   //Logic here

   return PartialView();

}

Q63. What is the latest version of ASP.NET MVC?

Answer: MVC 6 is the latest version which is also termed as ASP VNEXT.


Related Posts



Comments

Recent Posts
Tags