Share this:

Top 103 MVC Questions and Answers for Job Interview :

1.  Explain the MVC Pattern.

Answer : The Model View Controller or MVC is an architectural pattern used for building applications that separate data from the user interface and the processing.

2. List the action filters in MVC.

Answer : The following types of action filters are provided by the ASP.NET MVC.

  • Authorization filter: This makes security decisions about whether to execute an action method or not. The AuthorizeAttribute class is one example of an Authorization Filter.
  • Action filter: This wraps the action method execution and can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method.
  • Result filter:This wraps execution of the ActionResult object and can perform additional processing of the result, such as modifying the HTTP response. The OutputCacheAttribute class is an example of the Result Filter.
  • Exception filter:This is executed if there is an unhandled exception thrown somewhere in the action method, starting with the authorization filters and ending with the execution of the result. Exception filters can be used for logging or displaying an error page. The HandleErrorAttribute class is an example of the Exception Filter.

3. In which order is execution carried out if multiple Action Filters are implemented?

Answer : The following system of execution is implemented when there are multiple Action Filters:

  • Authorization filter
  • Action filter
  • Result filter
  • Exception filter

4. What are ASP.NET MVC view engines?

Answer : The following can be considered as ASP.NET MVC view engines:

  • Web Forms view engine (ASPX)
  • Razor
  • Open-source view engines such as Spark, NHaml, or Django

 5. Explain ASP.NET MVC model binders.

Answer : The following list describes available ASP.NET MVC model binders and associated data types.

  • ByteArrayModelBinder(System.byte[]): This maps a browser request to a byte array.
  • LinqBinaryModelBinder(System.Data.Linq.Binary): This maps a browser request to a LINQ System.Data.Linq.Binary object.
  • FormCollectionModelBinder: This maps a browser request to a System.Web.Mvc.FormCollection.
  • HttpPostedFileBaseModelBinder(System.Web.HttpPostedFileBase): This binds a model to a hosted file.
  • Default Model Binders: The supported types for the DefaultModelBinder are Primitive types, such as String etc., Model classes, and generic collections List etc.
  • Data Annotation Model Binderto perform validation within an ASP.NET MVC application Custom Model Binders.

6. Explain the page lifecycle of ASP.NET MVC.

Answer : The following steps are performed by the ASP.Net MVC page:
1) App initialization
2) Routing
3) Instantiate and execute controller
4) Locate and invoke controller action
5) Instantiate and render view

7. Explain Data Annotation.

Answer : When you the Data Annotations Model Binder is used, the validator attributes are used to perform validation. The System.ComponentModel.DataAnnotations namespace comprises the following validator attributes:

  • Range – It enables you to validate the value of a property falls and checks whether it falls between a specified range of values.
  • Regular Expression – It enables us to validate whether the value of property matches a specified regular expression pattern.
  • Required – It enables us to mark a property as required.
  • String Length – It enables us to specify a maximum length for a String property.
  • Validation – It is the base class for all validator attributes.

8. Explain Inversion of Control (IoC) Containers.

Answer : The following are the Inversion of Control (IoC) containers generally used:

  • Unity (Microsoft Unity Application Block)
  • StructureMap
  • CastleWindsor
  • Ninject
  • Spring.NET
  • Autofac

9. What is Dependency Injection?

Answer : Dependency Injection or Inversion of Control (IoC), can be used as a technique for building loosely coupled applications. It provides ways to handle the dependencies between objects.

10. Explain MVC Passive View Architecture.

Answer : The significant change with Passive View is that the view is made completely passive and is no longer responsible for updating itself from the model. As a result, all of the view logic is in the controller. Hence, there is no dependency in either direction between the view and the model.

  • View– Views are event-driven Wave Forms. No business view is not written here. As followed MVC passive view pattern, the view does not talk to Model.
  • Controller-All the service calls will happen through the Controller. UI logic and validations are written here.
  • Model– The Model contains Entities, Repositories, and Services and all the business logic are written here.

11. Mention the significance of ASP.NET routing.

Answer : The ASP.NET MVC uses ASP.NET routing in order to map incoming browser requests to controller action methods. The ASP.NET Routing makes use of route table. The route table is created when the web application first starts. The route table is present in the Global.asax file.

12. Mention the 3 segments of the default route that is present in an ASP.NET MVC application.

Answer : The following segments are present in any ASP.NET NVC Application:

  • 1st Segment – Controller Name
  • 2nd Segment – Action Method Name
  • 3rd Segment – Parameter that is passed to the action method

13. Mention the significance of the NonActionAttribute.

Answer : In general, all public methods of any controller class are treated as action methods.
In order to prevent this default behavior, decorate the public method with NonActionAttribute.

14. Mention the advantages of ASP.NET MVC.

Answer : The following are the advantages of the ASP.NET MVC:

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

15. What do you mean by TempData in ASP.NET MVC?

Answer : TempData is a very short-lived instance, and one should only use it during the current and the subsequent requests only. TempData is a session, so they’re not entirely different. However, the distinction is easy to understand, because TempData is used only for redirects.

16. Explain ViewData in ASP.NET MVC.

Answer : For MVC data is usually maintained when the hit comes to the controller and reaches the view and finally, the scope of the data expires. ViewData is the new session management technique that has been introduced in ASP.NET MVC framework. The controller can add key/values pairs to the ViewData. The data is then passed to the view when the view is rendered. The view can add to or change the data, which will be sent to the controller when the view is posted as part of a request.

17. Explain ViewBag in ASP.NET MVC.

Answer : MVC 2 controllers support a ViewData property that permits one to pass data to a view template using a late-bound dictionary API. In MVC 3, one can also use the simpler syntax with the ViewBag property to accomplish the same purpose.

18.Explain the different return type controllers action methods supported by ASP.NET MVC.

Answer : There are about 11 kinds of return types in MVC:

  1. ViewResult– It renders a specified view of the response stream.
  2. PartialViewResult– It renders a specified partial view to the response stream.
  3. EmptyResult– It provides the user with an empty response.
  4. RedirectResult – It performs an HTTP redirection to a specified URL.
  5. RedirectToRouteResult– It performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data.
  6. JsonResult – It serializes a given ViewData object to the JSON format.
  7. JavaScriptResult – It returns a piece of JavaScript code that can be executed on the client.
  8. ContentResult– It writes content to the response stream without requiring a view.
  9. FileContentResult– It returns a file to the client.
  10. FileStreamResult– It returns a file to the client, which is provided by a Stream.
  11. FilePathResult– It returns a file to the client.

19. What do you know about Asynchronous Controller in ASP.NET MVC?

Answer : The asynchronous controller enables one to write asynchronous action methods. It allows one to perform long-running operations without making the running thread idle. The asynchronous action methods are useful when action must perform several independent long-running operations.

20. What do you mean by WebAPI in MVC4?

Answer : The WebAPI is the technology by which one can expose data over HTTP following REST principles. The WebAPI is built from scratch and the only goal is to create HTTP services using REST.

21. Differentiate between WebAPI and Controller in MVC4.

Answer : The following differences have been noticed:

  • Use Controller is used for rendering your normal views while the ApiController action only returns data that is serialized and sent to the client.
  • They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class.
  • Actions on Web API controllers do not return views, they return data.

22. Differentiate between ActionResult and ViewResult.

Answer : The ActionResult is an abstract class while the ViewResult is derived from the ActionResult class. The ActionResult has several derived classes like ViewResult, JsonResult, FileStreamResult and many more. The ActionResult can also be used to exploit polymorphism and dynamism.

23. Differentiate between tempdata and viewdata.

Answer : The following differences have been noted among the mentioned three:

  1. Temp data: -It helps to maintain data when one moves from one controller to another controller or from one action to another action. Tempdata helps to maintain data between those redirect from one action to another. It uses session variables, internally.
  2. View data: – It helps to maintain data when one moves from the controller to view.

24. What do you mean by MVC?

Answer : MVC is short for Model, View, and Controller. It is a software architectural pattern which separates the representation and user interaction.

  • Modelrepresents the real world objects and provides data to the view. It is a set of classes that describe business logic.
  • Viewis responsible for the look and feels and represents UI components like HTML, CSS, jQuery etc.
  • Controlleris responsible for taking the end user request via View and loading the appropriate Model and View for the same.

25. How do the Model, View, and Controller communicate with each other in ASP.NET MVC?

Answer : The user interacts with the controller. There is a one-to-many relationship between the controller and the view which means one controller can map to multiple views. The controller and the view can have a reference to the model. The controller and view can talk to each other. The model and the view cannot talk to each other directly. They communicate with each other with the help of a controller.

26. What are the advantages of the ASP.Net MVC over ASP.Net web Form?

Answer : The ASP.Net MVC has the following advantages over the ASP.Net Waveform:

  • The MVC framework provides a clean separation of the UI, Business Logic, Data or model.
  • Automated UI testing is possible because the internal code (UI interaction code) has moved to a simple .NET class. This gives one the opportunity to write unit tests and automate manual testing.
  • The ASP.NET MVC provides better control over HTML, CSS, and JavaScript than the traditional web form.
  • The ASP.NET MVC is lightweight because it doesn’t use ViewState and thus, reduces the bandwidth of the request.
  • The ASP.NET MVC supports most of the feature of ASP.NET web form like authentication and authorization, roles, caching, session etc.

27. Differentiate between the three-layer and MVC architecture.

Answer : The MVC architecture is the evolution of a three layered traditional architecture. Many components of the three layered architecture are part of the MVC. In the three-tier architecture, the client tier never communicates directly with the data tier. In a three-tier model, all communication must pass through the middle tier. The MVC architecture is triangular. The view sends updates to the controller, the controller updates the model, and the view gets updated directly from the model.

28. Explain the life cycle of the MVC application.

Answer : Any web application first understands the request and depending on the type of request, it sends out an appropriate response. There are two main phases in the life cycle of the MVC application: the creation of the request object and second is the sending of the response to the browser. The four major steps are:

Step 1: Fill Route: Every MVC request is mapped to a routeing table which specifies the controller and the action to be invoked. If it is the first request, it fills the route table with the route collection. This filling of route table happens in the Global.asax file.

Step 2: Fetching the Route: Depending on the URL sent the UrlRoutingModule searches the route table to create the RouteData object. The RouteData has the details about which the controller and action are to be invoked.

Step 3: Request context created: The RouteData object is used to create the RequestContext object.

Step 4: Controller instance created: The coming request object is sent to the MvcHandler instance to create the object of the controller class. Once the controller class object is created, it calls the “Execute” method of the controller class.

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

29. What are the different return types of controller action methods?

Answer : There are a total nine return types to return results from the controller to view. The base type of all these result types is ActionResult.

  1. ViewResult (View): It is used to return a webpage from an action method.
    2. PartialviewResult (Partialview): It is used to send a part of a view which will be rendered in another view.
    3. RedirectResult (Redirect): This return type is used to Redirects to another action method by using its URL.
    4. RedirectToRouteResult (RedirectToAction, RedirectToRoute): It is used to redirect to another action method.
    5. ContentResult (Content): It returns a user-defined content type.
    6. JsonResult (Json): This return type is used to return a serialized JSON object.
    7. JavaScriptResult(JavaScript): This return type is used to return JavaScript code that will run in a browser.
    8. FileResult(File): This return type is used to return binary output to write to the response.
    9. EmptyResult(): This return type is used to represent a return value that is used if the action method must return a null result (void).

30. Explain Routing in ASP.NET MVC.

Answer : The ASP.NET Routing module is responsible for mapping the incoming browser requests to some particular MVC controller actions. Routing is a pattern matching system that monitors the incoming request and figures out what to do with that request. Routing helps us to define a URL structure and map the URL with the controller.

31. Write the code to show how the URL structure, mapping with controller and action is defined.

Answer : Follow the given code to study how the URL structure, mapping with a controller and how an action is defined.

 public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.MapRoute(
“Default”,                                              // Route name
“{controller}/{action}/{id}”,                           // URL with parameters
new { controller = “Home”, action = “Index”, id = “” }  // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}

32. Explain the attributes-based routing in MVC.

Answer : By using the “Route” attribute we can easily define URL structure. Attribute routing provides us with more control over the URLs by defining routes directly on actions and controllers in your ASP.NET MVC application and WEB API.

33. How to define attributes-based routing in MVC.

Answer : In the given code, the “GotoContact” action has been modified with the route attribute. The route attribute says that the “GotoContact” can be invoked using the URL structure “Users/contact”.
public class HomeController: Controller
{
[Route(“Users/contact”)]
public ActionResult GotoContact()
{
return View();
}
}

34. How do we enable attribute routing in ASP.NET MVC?

Answer : To enable attribute routing in any ASP.NET MVC5 application, we just need to add a call to routes.MapMvcAttributeRoutes() method within RegisterRoutes() method of RouteConfig.cs file.

35. Write a piece of code to show the enabling of attribute routing in ASP.NET MVC.

Answer : Follow the piece of code to understand the enabling of attribute routing:

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

36. Differentiate between URL Rewriting and Routing.

Answer : Routing is focused on mapping a URL to a resource while URL Rewriting is focused on mapping one URL to another URL. URL rewriting rewrites an old URL to a new one while routing never rewrites the old URL to a new one but it maps to the original route.

37. How to maintain a Session in MVC?

Answer : Sessions can be maintained in MVC using three ways:

  1. TempData
  2. ViewData
  3. ViewBag

38. Differentiate between ViewData, ViewBag, and TempData.

Answer :

  • ViewData: It helps to maintain data when we move from controller to view. It is derived from the ViewDataDictionary class. It is available for the current request only and also requires typecasting for complex data.
  • ViewBag:It also helps to maintain data when we move from the controller to the view. It uses dynamic keyword internally. It is also available for the current request only and typecasting is not required.
  • TempData:It is derived from the TempDataDictionary class. Tempdata helps to maintain data when we move from one controller to another controller or from one action to another action. It requires typecasting for complex data.

39. Explain Partial View in ASP.NET MVC.

Answer : Partial view is a reusable view (like a user control). A partial view is a view that is rendered within another view which means it can be embedded inside another view. The partial view can be rendered using Html.Partial(), Html.RenderPartial(), Html.RenderAction() method.

40. Differentiate between View and Partial View.

Answer : The properties of ‘View’ are:

  • It contains the layout page.
  • Before any view is rendered, the ViewStart page is rendered.
  • It is not lightweight as compared to Partial View.
  • View might have a markup tag like HTML, head, title, body etc.

The properties of ‘Partial View’ are:

  • Partial view does not contain the layout page.
  • We can pass regular view to the render partial method.
  • Partial view is designed specially to render within the view.
  • Partial View is lightweight compared to View.
  • Partial view can be embedded inside another view.

41. What are the HTML helpers in ASP.NET MVC?

Answer : Html helpers are methods that return an HTML string. HTML helpers help us to render HTML controls in the view. They do not have an event model and a view state. We can also create our own HTML Helpers to render more complex content. There are three types of HTML helpers.

  • Inline HTML helpers
  • Built-in HTML helpers
  • Custom HTML helper

42. Mention the helpers present in the Built-in HTML helpers.

Answer : The Built-in helpers have the following HTML helpers:

  • Standard HTML helpers
  • Strongly type HTML helpers
  • Templated HTML Helpers

43. How to add an HTML textbox to a View?

Answer : In order to add a HTML textbox on view, the following HTML helper must be used:

<%=Html.TextBox(“Name”)%>

44. Differentiate between HTML.TextBox and HTML.TextBoxFor.

Answer : HTML.TextBoxFor is of the strongly typed while HTML.TextBox is not, but they both produce the same HTML. Using the typed “TextBoxFor” version allows using compile time checking. So if we change our model then we can check for any kinds of errors in their views.

45. How to do validation in ASP.NET MVC?

Answer : The ASP.NET MVC uses DataAnnotations attributes to implement validations and is one of the easiest ways to do validation in MVC.

46. Write a code to do validation in ASP.NET MVC.

Answer : In the code extract below there is a simple Employee class with a property EmpCode. This EmpCode property is tagged with a Required data annotation attribute.
public class Employee
{
[Required(ErrorMessage=”Emp code is required”)]
public string EmpCode
{
set;
get;
}
}

47. How to display a validation error message?

Answer : The following code can be used to display a validation error message:

<% using (Html.BeginForm(“PostEmployee”, “Home”, FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.EmpCode)%>
<%=Html.ValidationMessageFor(m => m.EmpCode)%>
<input type=”submit” value=”Submit Employee data” />
<%}%>

48. How to check if the model is proper or not in the controller?

Answer : The following piece of code can be executed for the given:

public ActionResult PostEmployee(Employee obj)
{
if (ModelState.IsValid)
{
obj.Save();
return View(“Thanks”);
}
else
{
return View(“Employee”);
}
}

49. Explain validation summary.

Answer : The validation summary is used to display all the error messages in the view. It displays an unordered list of all validation errors in the ModelState dictionary object.

50. Show examples of validation summary.

Answer : These are some of the examples:

@Html.ValidationSummary(true) @*//shows model-level errors*@
@Html.ValidationSummary(false) @*//shows model-level and property-level errors*@

51. What is the View Engine?

Answer : The View Engine is responsible for rendering a view into HTML form to the browser. By default, the Asp.net MVC supports Web Form(ASPX) and Razor View Engine. There are many third-party view engines (like Spark, Nhaml etc.) that are also available for Asp.net MVC.

52. Explain Razor.

Answer : The Razor View Engine is an advanced view engine, available with the MVC 3.0 and later versions. Razor uses “@” character instead of “<% %>” as used by the ASPX View Engine. It is compact, expressive and also reduces typing.

53. Mention the advantages of the Razor View Engine over the Web Form Engine.

Answer : These are the following advantages of the Razor View Engine over the Web Form Engine:

  • Razor syntax is very compact that reduces typing, whereas the Web Form Engine has the syntax which is same as an ASP.Net form application.
  • The namespace for Razor Engine is System.Web.Razor and the namespace for Webform Engine are System.Web.Mvc.WebFormViewEngine.
  • Razor view engine uses @ symbol to render server-side content. The Web Form Engine uses “<%= %>” or “<%: %>” to render server-side content.
  • The Razor engine supports test-driven development (TDD). Webform view engine does not support test driven development.
  • Razor has no file dependency. ASPX files have a dependency on the ASP.NET runtime to parse and execute those ASPX files.
  • The Razor View Engine prevents Cross Site Scripting (XSS) attacks by encoding the script or HTML tags before rendering to the view. A web form View engine does not prevent Cross Site Scripting (XSS) attack.
  • Razor engine doesn’t support design mode in visual studio. Web form engine supports design mode in visual studio, means we can see the look and feel of our page without running the application.

54. How to implement Windows Authentication for MVC?

Answer : The following piece of code is used to implement Windows Authentication for MVC:

<system.web>
<authentication mode=”Windows”/>
<authorization>
<deny users=”?”/>
</authorization>
</system.web>

55. How to implement Form Authentication for MVC?

Answer : The following piece of code is used to implement Form Authentication for MVC:

<system.web>
<authentication mode=”Forms”>
<forms loginUrl=”∼/Home/Login”  timeout=”20″/>
</authentication>
</system.web>

56. What do you mean by Areas in MVC?

Answer : The Area allows partitioning of a large application into smaller units where each unit contains separate MVC folder structure, same as default MVC folder structure. 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.

57. What do you mean by ViewStart?

Answer : The ViewStart.cshtml page is a special view page containing the statement declaration to include the Layout page. When a View Page Start is running, the ViewStart.cshtml page will assign the Layout page for it.

58. When do we use ViewStart?

Answer : The ViewStart.cshtml page is used to serve the same layout for a group of views. The code within this file is executed before the code in any view placed in the same directory. Therefore, a view can override the Layout property and choose a different one.

59. Differentiate between ActionResult and ViewResult.

Answer : In ASP.NET MVC, the classes ActionResult and ViewResult mainly return types for Controller Action method. The ActionResult is an abstract class while the ViewResult class derives from the ActionResult class. The ViewResult can return only a ViewResult type. The ActionResult can return many types of Result. If we are returning different types of view dynamically then the ActionResult is the one to be used.

60. How to use ActionResult?

Answer : The following code can be executed to use the ActionResult correctly:

public ActionResult DynamicView()
{
if (IsHtmlView)
return View(); // returns simple ViewResult
else
return Json(); // returns JsonResult view
}

61. How to use ViewResult?

Answer : The following code can beexecuted to use the ViewResult correctly:

public ViewResult Index()
{
return View();
}

62. What do you know about Filters in MVC?

Answer : The ASP.NET MVC filter is a custom class where we can write our custom logic to execute before or after Action method execute. The filter can be applied to an action method or controller. The filter provides the feature to add and post action behaviors on controller’s action methods.

63. Mention the various types of Filters in MVC.

Answer : The various types of filters present in MVC are:

  • Action Filters: They perform some operations before and after an action method is executed and implemented in the IActionFilter attribute.
  • Authorization Filters:They used to implement authentication and authorization for controller actions and implements the IAuthorizationFilter attribute.
  • Result Filters:The result filters contain logic that is executed before and after a view result is executed and implement the IResultFilter attribute.
  • Exception Filter:We use the exception filter to handle errors raised by either our controller or controller action results and implements the IExceptionFilter attribute.

64. What do you know about Action Filters in MVC?

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

65. What are the different types of Action Filters in MVC?

Answer : The different types of Action Filters in MVC are:

  • Output Cache:The Output action filter caches the output of a controller action for a specified amount of time.
  • Handle Error:The Handle 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.

66. Mention the different ways of handling an error in MVC.

Answer : Exception handling is the required part of each application. There are multiple ways to handle an exception in ASP.NET MVC.

  • Using the try-catch block
  • Override OnException Method
  • Using HandlerError Attribute
  • Global Error Handling

67. How to use and define the HandleError attributes?

Answer : public class HomeController: Controller
{
[HandleError()]
public ActionResult Index()
{
throw new Exception(“Demo”);
}
}

The given code can be used to define a HandleError attribute.

68. What is Bundling in MVC?

Answer : Bundling helps us combine multiple JavaScript and CSS files into a single entity thus minimizing multiple requests into a single request. The concept of Bundling was introduced in MVC 4 and .NET framework 4.5. It is used to reduce the number of requests to the server and size of requested CSS and JavaScript, which improves page loading time.

69. What is Minification in MVC?

Answer : Minification is a technique used for removing unnecessary characters (like white space, newline, tab) and comments from the JavaScript and CSS files to reduce the size which causes improved load times of a webpage. The concept of Bundling was introduced in MVC 4 and .NET framework 4.5. It is used to reduce the number of requests to the server and size of requested CSS and JavaScript, which improves page loading time.

70. What is GET Action Types?

Answer : GET is used to request data from a specified resource. With the entire GET request we pass the URL which is compulsory. However, it can take the following overloads: .get(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ).done/.fail

71. What is POST Action Types?

Answer : POST is used to submit data to be processed to a specified resource. With all the POST requests we pass the URL (compulsory) and the data. They can take the following overloads: .post(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

72. What do you know about Scaffolding?

Answer : Scaffolding is the technique for code generation for ASP.NET web application. This technique is used by many MVC frameworks like ASP.NET MVC, Node JS etc. for code generation. By using Scaffolding, we can reduce the amount of time to develop standard data operation in our project.

73. What are Scaffolding Templates?

Answer : Page templates, entity page templates, field page templates, and filter templates are known as the Scaffolding templates.

74. Explain JsonResult in MVC.

Answer : JavaScript Object Notation or JSON is a lightweight text-based open standard designed for human-readable data interchange. It provides an efficient mechanism to exchange data between the web browser and the web server. It is an open standard format. The JsonResult represents a class that is used to send JSON-formatted content to the response. The format of data looks very easy to understand and the data object consists of attribute-value pairs. The JsonResult Class is inherited from the “ActionResult” abstract class. Action methods in controllers return JsonResult that can be used in AJAX application.

75. What is Caching?

Answer : Caching is used to enhance the performance of the ASP.NET MVC web application. It provides a way of storing frequently accessed data and reusing that data. In ASP.NET MVC, the OutputCache attribute is used for applying Caching. OutputCaching stores the output of a Controller in memory and if any other request comes for the same, it returns the output from cache result.

76. When do we use Caching?

Answer : We use caching in the following cases:

  • Avoid caching content which is unique for every user or rarely used.
  • Define a short cache expiration time rather than disabling caching.
  • Cache frequently uses the content.

77. What is Loose Coupling and how is it implemented?

Answer : Loose coupling is a software design where all classes can work independently without relying on each other. MVC design pattern enables us to develop application’s components independently which allows testing and maintenance of our application easier.

78. How is Loose Coupling used?

Answer : One can develop loosely coupled application’s components by using Dependency InjectionYou.

79. Show code to implement Error Handling.

public class HomeController: Controller
{
protected override void OnException(ExceptionContext filterContext)
{
Exception ex = filterContext.Exception;
filterContext.ExceptionHandled = true;
var model = new HandleErrorInfo(filterContext.Exception, “Controller”,”Action”);
filterContext.Result = new ViewResult()
{
ViewName = “Error”,
ViewData = new ViewDataDictionary(model)
};
}
}

80. Explain Layout View.

Answer : ASP.NET MVC layout is like the Master page in the ASP web form. Using Layout view we maintain a consistent look and feel across all the pages within our web application. The layout may contain common jQuery, CSS file across multiple Views. The Layout view provides the code reusability that eliminates the duplicate code and enhances development speed and allows easy maintenance.

81. Provide a piece of code to show the implementation of the Layout View.

Answer :

<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″ />
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>@ViewBag.Title – My ASP.NET Application</title>
@Styles.Render(“∼ /Content/css”)
@Scripts.Render(“∼ /bundles/modernizr”)
</head>
<body>
<div class=”navbar navbar-inverse navbar-fixed-top”>
<div class=”container”>
<div class=”navbar-header”>
<button type=”button” class=”navbar-toggle” data-toggle=”collapse” data-target=”.navbar-collapse”>
<span class=”icon-bar”></span>
<span class=”icon-bar”></span>
<span class=”icon-bar”></span>
</button>
@Html.ActionLink(“Application name”, “Index”, “Home”, new { area = “” }, new { @class = “navbar-brand” })
</div>
<div class=”navbar-collapse collapse”>
<ul class=”nav navbar-nav”>
<li>@Html.ActionLink(“Home”, “Index”, “Home”)</li>
<li>@Html.ActionLink(“About”, “About”, “Home”)</li>
<li>@Html.ActionLink(“Contact”, “Contact”, “Home”)</li>
</ul>
</div>
</div>
</div>
<div class=”container body-content”>
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year – My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render(“∼ /bundles/jquery”)
@Scripts.Render(“∼ /bundles/bootstrap”)
@RenderSection(“scripts”, required: false)
</body>
</html>

82. What do you know about Sections in ASP.NET MVC?

Answer : A section allows us to define a region of content within a layout. It accepts one parameter which is the name of the section.

83. What are AJAX Helpers?

Answer : The feature known as the Ajax helpers of ASP.NET MVC provides the Ajax functionality to our web application. They are used to create Ajax enable elements like as Ajax enable form and links which perform request asynchronously. They are extension methods of AJAXHelper class which exist in System.Web.Mvc namespace.

84. Say something about Cross Domain AJAX.

Answer : By default, the web browser allows Ajax call only from the origin of the application where our site is hosted. This restriction helps us to prevent cross-site scripting (XSS) attacks. When we want to interact with externally hosted APIs, then our web application must support JSONP request or Cross-Origin Resource Sharing.

85. What do you know about NonAction attributes in ASP.Net MVC?

Answer : In the MVC framework, all the public methods of the controller class are treated as an Action method. If our controller class contains a public method and we do not want it to be an action method, then we must mark that method with the NonActionAttribute attribute.

86. What is exactly ASP.NET MVC?

Answer : ASP.NET MVC is a web development framework used for creating web applications on the ASP.NET platform. It is an alternative to web forms for creating web applications. It is based on the Model View Controller architectural pattern which used for creating loosely coupled applications.

87. What are the file extensions for razor views?

Answer : The file extensions used for Razor Views are:

  1. .cshtml – If the programming language is C#
  2. .vbhtml – If the programming language is VB

88. When using razor views, do you have to take any special steps to protect your asp.net MVC application from cross-site scripting (XSS) attacks?

Answer : No, by default content emitted using a ‘@ block’ is automatically HTML encoded to protect from cross-site scripting (XSS) attacks.

89. In razor syntax, what is the escape sequence character for @ symbol?

Answer : The escape sequence character for @ symbol is another @ symbol.

90. What symbol would you use to denote, the start of a code block in razor views?

Answer : The ‘@’ symbol is used to denote the start of a code black in Razor Views.

91. What symbol would you use to denote, the start of a code block in aspx views?

Answer : The ‘<%= %>’ symbol is used to denote the start of a code black in Razor Views.

92. What are the 2 popular ASP.NET MVC view engines?

Answer : The 2 most popular ASP.NET MVC View Engine:

  1. Razor
  2. .aspx

93. What type of filter does OutputCacheAttribute class represent?

Answer : The Result Filter represents the OutputCacheAttribute class.

94. What are the levels at which filters can be applied in an ASP.NET MVC application?

Answer :

1.Action Method
2.Controller
3. Application

95. Give examples for Authorization filters in ASP.NET MVC Applications.

Answer : RequireHttpsAttribute and AuthorizeAttribute filters are common examples of filters used in ASP.NET MVC Applications.

96. Mention 2 ways of adding constraints to a route.

Answer : The following ways are the general ways of adding constraints to a route:

  1. Use regular expressions
  2. Use an object that implements IRouteConstraint interface

97. How do you handle a variable number of segments in a route definition?

Answer : To handle a variable number of segments in a route definition, we generally use a route with a catch-all parameter.

An example is shown below:
controller/{action}/{*parametervalues}

98. What is the difference between adding routes to a webforms application and to a MVC application?

Answer : To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class, whereas to add routes to an MVC application we use MapRoute() method.

99. What is the use of the {resource}.axd/{*pathInfo}default route?
Answer : This route definition is used to prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.

100. Can the {controller}{action}/{id}route definition be considered a valid route definition?

Answer : No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.

101. What are the 3 things that are needed to specify a route?

Answer : The following three things are needed to specify a route:

  1. URL Pattern– You can include placeholders in a URL pattern so that the variable data can be passed to the request handler without requiring a query string.
    2. Handler – The handler can be a physical file such as a .aspx file or a controller class.
    3. Name for the Route – This is optional.

102. What is the advantage of using ASP.NET routing?

Answer : In an ASP.NET web application that does not make use of routing, an incoming browser request should map to a physical file. If the file does not exist, we get the page not found an error. An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user’s action and therefore are more easily understood by users.

103. Mention the significance of ASP.NET routing.

Answer : The ASP.NET MVC uses ASP.NET routing to map incoming browser requests to controller action methods. The ASP.NET Routing makes use of route table. Route table is created when the web application first starts. The route table is present in the Global.asax file.

 

Conclusion:

MVC is the new Buzz in the market. Though this architecture is adopted across the techologies like Java, PHP etc., ASP.NET MVC has disrupted the market. Majority of the legacy .NET projects and products have been migrating to MVC architecture and this trend will continue for few more years. Also, all new .NET projets will be default adopt MVC architecture. 103 MVC Interview questions listed above will make you stay ahead in the job market competition.

Share this: