If you’re looking for asp.net mvc  Interview Questions for Experienced & Freshers. Here we have mentioned some of the asp.net mvc interview questions asked in various MNCs. Also useful for MCTS, MCAD, MCSD and other Microsoft certification exams.

If there is any new asp.net mvc  interview question that have been asked to you, kindly post it in the the comment section.


 

1. Explain what is Model-View-Controller?

Ans:

MVC is a software architecture pattern for developing web application. It is handled by three objects Model-View-Controller.

2. Mention what does Model-View-Controller represent in an MVC application?

Ans:

In an MVC model,
Model– It represents the application data domain. In other words applications business logic is contained within the model and is responsible for maintaining data
View– It represents the user interface, with which the end users communicates. In short all the user interface logic is contained within the VIEW
Controller– It is the controller that answers to user actions. Based on the user actions, the respective controller responds within the model and choose a view to render that display the user interface. The user input logic is contained with-in the controller

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

Ans:

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

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

Ans:

  • View Result
  • Javascript Result
  • Redirect Result
  • Json Result
  • Content Result

5. Mention what is the difference between adding routes, to a webform application and an MVC application?

Ans:

To add routes to a webform application, we can use MapPageRoute() method of the RouteCollection class, where adding routes to an MVC application, you can use MapRoute() method.

6. Mention what are the two ways to add constraints to a route?

Ans:

The two methods to add constraints to a route is

  • Use regular expressions
  • Use an object that implements IRouteConstraint Interface

7. Mention what is the advantages of MVC?

Ans:

  • MVC segregates your project into a different segment, and it becomes easy for developers to work on
  • It is easy to edit or change some part of your project that makes project less development and maintenance cost
  • MVC makes your project more systematic

8. Mention what “beforFilter()”,“beforeRender” and “afterFilter” functions do in Controller?

Ans:

beforeFilter(): This function is run before every action in the controller. It’s the right place to check for an active session or inspect user permissions.
beforeRender(): This function is called after controller action logic, but before the view is rendered. This function is not often used, but may be required If you are calling render() manually before the end of a given action
afterFilter(): This function is called after every controller action, and after rendering is done. It is the last controller method to run

9. Explain the role of components Presentation, Abstraction and Control in MVC?

Ans:

Presentation: It is the visual representation of a specific abstraction within the application
Abstraction: It is the business domain functionality within the application
Control: It is a component that keeps consistency between the abstraction within the system and their presentation to the user in addition to communicating with other controls within the system

10. Mention the advantages and disadvantages of MVC model?

Ans:

Advantages

Disadvantages

  • It represents clear separation between business logic and presentation logic
  • Each MVC object has different responsibilities
  • The development progresses in parallel
  • Easy to manage and maintain
  • All classes and object are independent of each other
  • The model pattern is little complex
  • Inefficiency of data access in view
  • With modern user interface, it is difficult to use MVC
  • You need multiple programmers for parallel development
  • Multiple technologies knowledge is required


 

11. Explain the role of “ActionFilters” in MVC?

Ans:

In MVC “ ActionFilters” help you to execute logic while MVC action is executed or its executing.

12. Explain what are the steps for the execution of an MVC project?

Ans:

The steps for the execution of an MVC project includes

  • Receive first request for the application
  • Performs routing
  • Creates MVC request handler
  • Create Controller
  • Execute Controller
  • Invoke action
  • Execute Result

13. Explain what is routing? What are the three segments for routing is important?

Ans:

Routing helps you to decide a URL structure and map the URL with the Controller.

The three segments that are important for routing is

  • ControllerName
  • ActionMethodName
  • Parameter

14. Explain how routing is done in MVC pattern?

Ans:

There is a group of routes called the RouteCollection, which consists of registered routes in the application.  The RegisterRoutes method records the routes in this collection. A route defines a URL pattern and a handler to use if the request matches the pattern. The first parameter to the MapRoute method is the name of the route. The second parameter will be the pattern to which the URL matches.  The third parameter might be the default values for the placeholders if they are not determined.

15. Explain using hyperlink how you can navigate from one view to other view?

Ans:

By using “ActionLink” method as shown in the below code. The below code will make a simple URL which help to navigate to the “Home” controller and invoke the “GotoHome” action.

Collapse / Copy Code

<%= Html.ActionLink(“Home”, “Gotohome”) %>

16. Mention how can maintain session in MVC?

Ans:

Session can be maintained in MVC by three ways tempdata, viewdata, and viewbag.

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

Ans:

  • Temp data: It helps to maintain data when you shift from one controller to other controller.
  • View data: It helps to maintain data when you move from controller to view
  • View Bag: It’s a dynamic wrapper around view data

18. What is partial view in MVC?

Ans:

Partial view in MVC renders a portion of view content. It is helpful in reducing code duplication. In simple terms, partial view allows to render a view within the parent view.

19. Explain how you can implement Ajax in MVC?

Ans:

In Ajax, MVC can be implemented in two ways

  • Ajax libraries
  • Jquery

20. Mention what is the difference between “ActionResult” and “ViewResult” ?

Ans:

“ActionResult” is an abstract class while “ViewResult” is derived from “AbstractResult” class.  “ActionResult” has a number of derived classes like “JsonResult”, “FileStreamResult” and “ViewResult” .

“ActionResult” is best if you are deriving different types of view dynamically.




 

21. Explain how you can send the result back in JSON format in MVC?

Ans:

In order to send the result back in JSON format in MVC, you can use “JSONRESULT” class.

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

Ans:

                           View

                              Partial 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.
  • View is not lightweight as compare to 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 any mark up
  • We can pass a regular view to the RenderPartial method

23. List out the types of result in MVC?

Ans:

In MVC, there are twelve types of results in MVC where “ActionResult” class is the main class while the 11 are their sub-types

  • ViewResult
  • PartialViewResult
  • EmptyResult
  • RedirectResult
  • RedirectToRouteResult
  • JsonResult
  • JavaScriptResult
  • ContentResult
  • FileContentResult
  • FileStreamResult
  • FilePathResult

24. Mention what is the importance of NonActionAttribute?

Ans:

All public methods of a controller class are treated as the action method if you want to prevent this default method then you have to assign the public method with NonActionAttribute.

25. Mention what is the use of the default route {resource}.axd/{*pathinfo} ?

Ans:

This default route prevents request for a web resource file such as Webresource.axd or ScriptResource.axd from being passed to the controller.

26. Mention the order of the filters that get executed, if the multiple filters are implemented?

Ans:

The filter order would be like

  • Authorization filters
  • Action filters
  • Response filters
  • Exception filters

27. Mention what filters are executed in the end?

Ans:

In the end “Exception Filters” are executed.

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

Ans:

For razor views the file extensions are

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

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

Ans:

Two methods for adding constraints to route is

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

30. Mention two instances where routing is not implemented or required?

Ans:

Two instance where routing is not required are

  • When a physical file is found that matches the URL pattern
  • When routing is disabled for a URL pattern

 

31. Mention what are main benefits of using MVC?

Ans:

There are two key benefits of using MVC

  • As the code is moved behind a separate class file, you can use the code to a great extent
  • As behind code is simply moved to.NET class, it is possible to automate UI testing. This gives an opportunity to automate manual testing and write unit tests.

32. What is ASP.NET MVC?

Ans:

ASP.NET MVC is a web application Framework. It is light weight and highly testable Framework. MVC separates application into three components?—?Model, View and Controller.

33. Can you explain Model, Controller and View in MVC?

Ans:

Model—It’s a business entity and it is used to represent the application data.
Controller-Request sent by the user always scatters through controller and it’s responsibility is to redirect to the specific view using View() method.
View-It’s the presentation layer of MVC.

34. Explain the new features added in version 4 of MVC (MVC4)?

Ans:

Following are features added newly –
Asynchronous controller task support.
Bundling the java scripts.
Segregating the configs for MVC routing, Web API, Bundle etc.
Mobile templates
Added ASP.NET Web API template for creating REST based services.
Asynchronous controller task support.
Bundling the java scripts.
Segregating the configs for MVC routing, Web API, Bundle etc.

35. Can you explain the page life cycle of MVC?

Ans:

Below are the processed followed in the sequence –
App initialization
Routing
Instantiate and execute controller
Locate and invoke controller action
Instantiate and render view.

36. What are the advantages of MVC over ASP.NET?

Ans:

Provides a clean separation of concerns among UI (Presentation layer), model (Transfer objects/Domain Objects/Entities) and Business Logic (Controller).
Easy to UNIT Test.
Improved reusability of model and views. We can have multiple views which can point to the same model and vice versa.
Improved structuring of the code.

37. What is Separation of Concerns in ASP.NET MVC?

Ans:

It’s is the process of breaking the program into various distinct features which overlaps in functionality as little as possible. MVC pattern concerns on separating the content from presentation and data-processing from content.

38. What is Razor View Engine?

Ans:

Razor is the first major update to render HTML in MVC 3. Razor was designed specifically for view engine syntax. Main focus of this would be to simplify and code-focused templating for HTML generation.

39. What is the meaning of Unobtrusive JavaScript?

Ans:

This is a general term that conveys a general philosophy, similar to the term REST (Representational State Transfer). Unobtrusive JavaScript doesn’t intermix JavaScript code in your page markup.
Eg : Instead of using events like onclick and onsubmit, the unobtrusive JavaScript attaches to elements by their ID or class based on the HTML5 data- attributes.

40. What is the use of ViewModel in MVC?

Ans:

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



 

41. What you mean by Routing in MVC?

Ans:

Routing is a pattern matching mechanism of incoming requests to the URL patterns which are registered in route table. Class?—?“UrlRoutingModule” is used for the same process.

42. What are Actions in MVC?

Ans:

Actions are the methods in Controller class which is responsible for returning the view or json data. Action will mainly have return type?—?“ActionResult” and it will be invoked from method?—?“InvokeAction()” called by controller.

43. What is Attribute Routing in MVC?

Ans:

ASP.NET Web API supports this type routing. This is introduced in MVC5. In this type of routing, attributes are being used to define the routes. This type of routing gives more control over classic URI Routing. Attribute Routing can be defined at controller level or at Action level like –
[Route(“{action = TestCategoryList}”)]?—?Controller Level
[Route(“customers/{TestCategoryId:int:min(10)}”)]?—?Action Level

44. How to enable Attribute Routing?

Ans:

Just add the method?—?“MapMvcAttributeRoutes()” to enable attribute routing as shown below
public static void RegistearRoutes(RouteCollection routes)
{
routes.IgnoareRoute(“{resource}.axd/{*pathInfo}”);
//enabling attribute routing
routes.MapMvcAttributeRoutes();
//convention-based routing
routes.MapRoute
(
name: “Default”,
url: “{controller}/{action}/{id}”,
defaults: new { controller = “Customer”, action = “GetCustomerList”, id = UrlParameter.Optional }
);
}

45. Explain JSON Binding?

Ans:

JavaScript Object Notation (JSON) binding support started from MVC3 onwards via the new JsonValueProviderFactory, which allows the action methods to accept and model-bind data in JSON format. This is useful in Ajax scenarios like client templates and data binding that need to post data back to the server.

46. Explain Dependency Resolution?

Ans:

Dependency Resolver again has been introduced in MVC3 and it is greatly simplified the use of dependency injection in your applications. This turn to be easier and useful for decoupling the application components and making them easier to test and more configurable.

47. Explain Bundle.Config in MVC4?

Ans:

“BundleConfig.cs” in 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.

48. How route table has been created in ASP.NET MVC?

Ans:

Method-“RegisterRoutes()” is used for registering the routes which will be added in “Application_Start()” method of global.asax file, which is fired when the application is loaded or started.

49. Which are the important namespaces used in MVC?

Ans:

Below are the important namespaces used in MVC –
System.Web.Mvc
System.Web.Mvc.Ajax
System.Web.Mvc.Html
System.Web.Mvc.Async

50. What is ViewData?

Ans:

Viewdata contains the key, value pairs as dictionary and this is derived from class?—?“ViewDataDictionary“. In action method we are setting the value for viewdata and in view the value will be fetched by typecasting.




 

51. What is the difference between ViewBag and ViewData in MVC?

Ans:

ViewBag is a wrapper around ViewData, which allows to create dynamic properties. Advantage of viewbag over viewdata will be –
In ViewBag no need to typecast the objects as in ViewData.
ViewBag will take advantage of dynamic keyword which is introduced in version 4.0. But before using ViewBag we have to keep in mind that ViewBag is slower than ViewData.

52. Explain TempData in MVC?

Ans:

TempData is again a key, value pair as ViewData. This is derived from “TempDataDictionary” class. TempData is used when the data is to be used in two consecutive requests, this could be between the actions or between the controllers. This requires typecasting in view.

53. What are HTML Helpers in MVC?

Ans:

HTML Helpers are like controls in traditional web forms. But HTML helpers are more lightweight compared to web controls as it does not hold viewstate and events.
HTML Helpers returns the HTML string which can be directly rendered to HTML page. Custom HTML Helpers also can be created by overriding “HtmlHelper” class.

54. What are AJAX Helpers in MVC?

Ans:

AJAX Helpers are used to create 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 namespace?—?System.Web.Mvc.

55. What are the options can be configured in AJAX helpers?

Ans:

Below are the options in AJAX helpers –
Url-This is the request URL.
Confirm-This is used to specify the message which is to be displayed in 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.

56. What is Layout in MVC?

Ans:

Layout pages are similar to master pages in traditional web forms. This is used to set the common look across multiple pages. In each child page we can find?—?/p>
@{
Layout = “~/Views/Shared/TestLayout1.cshtml”;
}
This indicates child page uses TestLayout page as it’s master page.

57. Explain Sections is MVC?

Ans:

Section are the part of HTML which is to be rendered in layout page.

58. Can you explain RenderBody and RenderPage in MVC?

Ans:

RenderBody is like ContentPlaceHolder in web forms. This will exist in layout page and it will render the child pages/views. Layout page will have only one RenderBody() method. RenderPage also exists in Layout page and multiple RenderPage() can be there in Layout page.

59. What is ViewStart Page in MVC?

Ans:

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

60. Explain the methods used to render the views in MVC?

Ans:

Below are the methods used to render the views from action –
View()-To return the view from action.
PartialView()-To return the partial view from action.
RedirectToAction()-To Redirect to different action which can be in same controller or in different controller.
Redirect()-Similar to “Response.Redirect()” in webforms, used to redirect to specified URL.
RedirectToRoute()-Redirect to action from the specified URL but URL in the route table has been matched.


 

61. What are the sub types of ActionResult?

Ans:

ActionResult is used to represent the action method result. Below are the subtypes of ActionResult –

  • ViewResult
  • PartialViewResult
  • RedirectToRouteResult
  • RedirectResult
  • JavascriptResult
  • JSONResult
  • FileResult
  • HTTPStatusCodeResult

62. What are Non Action methods in MVC?

Ans:

In MVC all public methods have been treated as Actions. So if you are creating a method and if you do not want to use it as an action method then the method has to be decorated with “NonAction” attribute as shown below –

[NonAction]
public void TestMethod()
{
// Method logic
}

63. How to change the action name in MVC?

Ans:

“ActionName” attribute can be used for changing the action name. Below is the sample code snippet to demonstrate more –

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

64. What are Code Blocks in Views?

Ans:

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.

@{
int x = 123;
string y = “aa”;
}

65. What is the “HelperPage.IsAjax” Property?

Ans:

The HelperPage.IsAjax property gets a value that indicates whether Ajax is being used during the request of the Web page.

66. What is the meaning of Unobtrusive JavaScript?

Ans:

This is a general term that conveys a general philosophy, similar to the term REST (Representational State Transfer). Unobtrusive JavaScript doesn’t intermix JavaScript code in your page markup.
Eg : Instead of using events like onclick and onsubmit, the unobtrusive JavaScript attaches to elements by their ID or class based on the HTML5 data- attributes.

67. What are Validation Annotations?

Ans:

Data annotations are attributes which can be found in the “System.ComponentModel.DataAnnotations” namespace. These attributes will be used for server-side validation and client-side validation is also supported. Four attributes-Required, String Length, Regular Expression and Range are used to cover the common validation scenarios.

68. Why to use Html.Partial in MVC?

Ans:

This method is used to render the specified partial view as an HTML string. This method does not depend on any action methods. We can use this like below –
@Html.Partial(“TestPartialView”)

69. What is Html.RenderPartial?

Ans:

Result of the method-“RenderPartial” is directly written to the HTML response. This method does not return anything (void). This method also does not depend on action methods. RenderPartial() method calls “Write()” internally and we have to make sure that “RenderPartial” method is enclosed in the bracket. Below is the sample code snippet –@{Html.RenderPartial(“TestPartialView”); }

70. What is RouteConfig.cs in MVC 4?

Ans:

“RouteConfig.cs” holds the routing configuration for MVC. RouteConfig will be initialized on Application_Start event registered in Global.asax.



 

71. What are Scaffold templates in MVC?

Ans:

Scaffolding in ASP.NET MVC is used to generate the Controllers,Model and Views for create, read, update, and delete (CRUD) functionality in an application. The scaffolding will be knowing the naming conventions used for models and controllers and views.

72. Explain the types of Scaffoldings.

Ans:

Below are the types of scaffoldings –

  • Empty
  • Create
  • Delete
  • Details
  • Edit
  • List

73. Can a view be shared across multiple controllers? If Yes, How we can do that?

Ans:

Yes, we can share a view across multiple controllers. We can put the view in the “Shared” folder. When we create a new 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.

74. What are the components required to create a route in MVC?

Ans:

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.

75. Why to use “{resource}.axd/{*pathInfo}” in routing in MVC?

Ans:

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.

76. Can we add constraints to the route? If yes, explain how we can do it?

Ans:

Yes we can add constraints to route in following ways –

  • Using Regular Expressions
  • Using object which implements interface-IRouteConstraint.

77. What are the possible Razor view extensions?

Ans:

Below are the two types of extensions razor view can have –

  • .cshtml-In C# programming language this extension will be used.
  • .vbhtml-In VB programming language this extension will be used.

78. What is PartialView in MVC?

Ans:

PartialView is similar to UserControls in traditional web forms. For re-usability purpose partial views are used. Since it’s been shared with multiple views these are kept in shared folder. Partial Views can be rendered in following ways –

  • Html.Partial()
  • Html.RenderPartial()

79. How we can add the CSS in MVC?

Ans:

The sample code snippet to add css to razor views.

 

80. Can I add MVC Testcases in Visual Studio Express?

Ans:

No. We cannot add the test cases in Visual Studio Express edition it can be added only in Professional and Ultimate versions of Visual Studio.




 

81. What is the use .Glimpse in MVC?

Ans:

Glimpse is an open source tool for debugging the routes in MVC. It is the client side debugger. This is a popular and useful tool for debugging which tracks the speed details.

82. What is MVC (Model View Controller)

Ans:

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

83. What is MVC Application Life Cycle

Ans:

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.

MVC Application Life Cycle

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

Ans:

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

85. What are the advantages of MVC

Ans:

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.

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

Ans:

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.

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

Ans:

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

88. What are Filters in MVC?

Ans:

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.

89. What are Action Filters in MVC?

Ans:

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”);

}

}

90. What are HTML helpers in MVC?

Ans:

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”) %>


 

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

Ans:

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

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

Ans:

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.

MVC

93. Where is the route mapping code written?

Ans:

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

94. What is the difference between Temp data, View, and View Bag?

Ans:

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

95. What is Partial View in MVC?

Ans:

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.

96. How did you create a partial view and consume it?

Ans:

When you add a view to your project you need to check the “Create partial view” check box.
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:

<% Html.RenderPartial(“MyView”); %>

 

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

Ans:

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.
  • View is not lightweight as compare to Partial View.

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 any mark up.
  • We can pass a regular view to the RenderPartial method.

98. Explain attribute based routing in MVC?

Ans:

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();

}

}

99. What is Razor in MVC?

Ans:

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.

100. How to implement Forms authentication in MVC?

Ans:

ASP.NET forms authentication occurs after IIS authentication is completed. You can configure forms authentication by using forms element with in web.config file of your application. The FormsAuthentication class creates the authentication cookie automatically when SetAuthCookie() or RedirectFromLoginPage() methods are called. The value of authentication cookie contains a string representation of the encrypted and signed FormsAuthenticationTicket object.



 

101. What is Areas in MVC?

Ans:

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:

Areas in 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.

102. Explain the concept of MVC Scaffolding?

Ans:

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.

Scaffolding Templates:

Create: It creates a View that helps in creating a new record for the Model. It automatically generates a label and input field for each property in the Model.

Delete: It creates a list of records from the model collection along with the delete link with delete record.

Details: It generates a view that displays the label and an input field of the each property of the Model in the MVC framework.

Edit: It creates a View with a form that helps in editing the current Model. It also generates a form with label and field for each property of the model.

List: It generally creates a View with the help of a HTML table that lists the Models from the Model Collection. It also generates a HTML table column for each property of the Model.

103. What is the difference between ActionResult and ViewResult?

Ans:

  • 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.
public ActionResult DynamicView()

{

if (IsHtmlView)

return View(); // returns simple ViewResult

else

return Json(); // returns JsonResult view

}

104. What is Output Caching in MVC?

Ans:

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.
OutputCache label has a “Location” attribute and it is fully controllable. Its default value is “Any”, however there are the following locations available; as of now, we can use any one.

  • Any
  • Client
  • Downstream
  • Server
  • None
  • ServerAndClient

105. What is the use of Keep and Peek in “TempData”?

Ans:

Once “TempData” is read in the current request it’s not available in the subsequent request. If we want “TempData” to be read and also available in the subsequent request then after reading we need to call “Keep” method as shown in the code below.
@TempData[“MyData”];
TempData.Keep(“MyData”);
The more shortcut way of achieving the same is by using “Peek”. This function helps to read as well advices MVC to maintain “TempData” for the subsequent request.
string str = TempData.Peek(“MyData “).ToString();

106. What is Bundling and Minification in MVC?

Ans:

Bundling and minification are two new techniques introduced to improve request load time. It improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript).

Bundling: It lets us combine multiple JavaScript (.js) files or multiple cascading style sheet (.css) files so that they can be downloaded as a unit, rather than making individual HTTP requests.
Minification: It squeezes out whitespace and performs other types of compression to make the downloaded files as small as possible. At runtime, the process identifies the user agent, for example IE, Mozilla, etc. and then removes whatever is specific to Mozilla when the request comes from IE.

107. What is Validation Summary in MVC?

Ans:

The ValidationSummary helper method generates an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.
The ValidationSummary can be used to display all the error messages for all the fields. It can also be used to display custom error messages. The following figure shows how ValidationSummary displays the error messages.

108. What are the Folders in MVC application solutions?

Ans:

When you create a project a folder structure gets created by default under the name of your project which can be seen in solution explorer. Below I will give you a brief explanation of what these folders are for.
Model: This folder contains classes that is used to provide data. These classes can contain data that is retrieved from the database or data inserted in the form by the user to update the database.
Controllers: These are the classes which will perform the action invoked by the user. These classes contains methods known as “Actions” which responds to the user action accordingly.
Views: These are simple pages which uses the model class data to populate the HTML controls and renders it to the client browser.
App_Start: Contains Classes such as FilterConfig, RoutesConfig, WebApiConfig. As of now we need to understand the RouteConfig class. This class contains the default format of the URL that should be supplied in the browser to navigate to a specified page.

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

Ans:

  • Authorization filters
  • Action filters
  • Response filters
  • Exception filters

110. What is ViewStart?

Ans:

Razor View Engine introduced a new layout named _ViewStart which is applied on all view automatically. Razor View Engine firstly executes the _ViewStart and then start rendering the other view and merges them.
Example of Viewstart:

@ { 
Layout = "~/Views/Shared/_v1.cshtml";
} < !DOCTYPE html >
< html >
< head >
< meta name = "viewport"
content = "width=device-width" / >
< title > ViewStart < /title> < /head> < body >
< /body> < /html>



 

111. What is JsonResultType in MVC?

Ans:

Action methods on controllers return JsonResult (JavaScript Object Notation result) that can be used in an AJAX application. This class is inherited from the “ActionResult” abstract class. Here Json is provided one argument which must be serializable. The JSON result object that serializes the specified object to JSON format.

public JsonResult JsonResultTest() 
{
return Json("Hello My Friend!");
}

112. What are the Difference between ViewBag&ViewData?

Ans:

ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
ViewData requires typecasting for complex data type and check for null values to avoid error.
ViewBag doesn’t require typecasting for complex data type.

Calling of ViewBag is:

ViewBag.Name = "Vikash";
Calling of ViewData is :
ViewData["Name"] = " Vikash ";

113. Explain RenderSection in MVC?

Ans:

RenderSection() is a method of the WebPageBase class. Scott wrote at one point, The first parameter to the “RenderSection()” helper method specifies the name of the section we want to render at that location in the layout template. The second parameter is optional, and allows us to define whether the section we are rendering is required or not. If a section is “required”, then Razor will throw an error at runtime if that section is not implemented within a view template that is based on the layout file (that can make it easier to track down content errors). It returns the HTML content to render.

 

 

114. What is GET and POST Actions Types?

Ans:

GET
GET is used to request data from a specified resource. With all the 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

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

115. What is display mode in MVC?

Ans:

Display mode displays views depending on the device the user has logged in with. So we can create different views for different devices and display mode will handle the rest.
For example we can create a view “Home.aspx” which will render for the desktop computers and Home.Mobile.aspx for mobile devices. Now when an end user sends a request to the MVC application, display mode checks the “user agent” headers and renders the appropriate view to the device accordingly.

116. How can we do exception handling in MVC?

Ans:

In the controller you can override the “OnException” event and set the “Result” to the view name which you want to invoke when error occurs. In the below code you can see we have set the “Result” to a view named as “Error”.
We have also set the exception so that it can be displayed inside the view.

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)
};
}
}

To display the above error in view we can use the below code
@Model.Exception;

117. What is the use of remote validation in MVC?

Ans:

Remote validation is the process where we validate specific data posting data to a server without posting the entire form data to the server. Let’s see an actual scenario, in one of my projects I had a requirement to validate an email address, whether it already exists in the database. Remote validation was useful for that; without posting all the data we can validate only the email address supplied by the user.
Let’s create a MVC project and name it accordingly, for me its “TestingRemoteValidation”. Once the project is created let’s create a model named UserModel that will look like:

public class UserModel 
{
[Required]
public string UserName
{
get;
set;
}
[Remote("CheckExistingEmail", "Home", ErrorMessage = "Email already exists!")]
public string UserEmailAddress
{
get;
set;
}
}

Let’s get some understanding of the remote attribute used, so the very first parameter “CheckExistingEmail” is the the name of the action. The second parameter “Home” is referred to as controller so to validate the input for the UserEmailAddress the “CheckExistingEmail” action of the “Home” controller is called and the third parameter is the error message. Let’s implement the “CheckExistingEmail” action result in our home controller.

public ActionResult CheckExistingEmail(string UserEmailAddress) 
{
bool ifEmailExist = false;
try
{
ifEmailExist = UserEmailAddress.Equals("mukeshknayak@gmail.com") ? true : false;
return Json(!ifEmailExist, JsonRequestBehavior.AllowGet);
} catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}

118. Explain Dependency Resolution?

Ans:

Dependency Resolver again has been introduced in MVC3 and it is greatly simplified the use of dependency injection in your applications. This turn to be easier and useful for decoupling the application components and making them easier to test and more configurable.

119. Explain Bundle.Config in MVC4?

Ans:

“BundleConfig.cs” in 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.