Translate to your language...

13 April 2017

ASP.Net MVC related questions

Hi Friends,
Now days, there are many companies asking about the ASP.Net MVC related questions in their interview process. So I thought of keeping few questions related to MVC and ASP.Net MVC. These questions will be help to all those who are attending the interviews or preparing for the ASP.Net MVC related questions.

Here I am keeping the questions related to all the versions of ASP.Net MVC by keeping in mind that interviewer can ask the questions from any aspect.

1.    What is MVC? 
Ans. MVC (Model View Controller) is one of the Software Architectural patterns which is built on 3 layers- Model layer, View layer and Controller layer. MVC is a pattern which basically talks about the separation of concern for a project where each of these layer is separate without any dependency. 
Here the 3 layers having their own individual roles like:
a. Model - It is used as the Data Container. Mainly we write the public properties under this layer. Properties are the data carrier to cater the data from one layer to another layer.
e.g.
public string FullName {get; set;}
It is not the good practice to write the business logic here so we should keep avoiding the business rules, functions, logic's in this layer etc.
b. View - It is mainly the UI (User Interface) part which is the main application built using the Web technologies like ASP.Net etc. It consists of the User Interface Design, representation of the information for the end users etc.
c. Controller - It is the mediator between the View and Model and used to control the requests and responses floating through the views and Model. The command, Actions, Events are the part of Controller in MVC. All the communication is done via Controller so we can say that Controller is the heart of MVC.

2.    What is ASP.Net MVC? 
Ans. ASP.Net MVC is the Microsoft product based on the core MVC pattern. The Microsoft has taken the core concept of MVC and Designed the ASP.Net MVC structure for the Visual Studio which helps the developers to get the automated structure and on it, they can built the applications.
ASP.Net MVC provides the structure with the separation of concerns where each part of ASP.Net MVC application is separate and has no link among them. Apart from the separation of concerns, the Microsoft has provided the way to communicate between the separate components by using the other additional logic and libraries. These libraries supports in the connection, communication between the components, databases and other external components as well with small effort.

3.    How ASP.Net MVC is different than MVC?
Ans. ASP.Net MVC is the inherited form of Core MVC where Microsoft has designed their MVC patterns based on the original core MVC concept. The Microsoft also provided the new MVC structure (ASP.Net MVC) which has the inbuilt capabilities of communication with their components, connection with the database etc. The ASP.Net MVC has the good support for creating mobile application. We can create the Mobile applications in ASP.Net MVC using the predefined template.

4.    What are the new features of ASP.Net MVC 2?
Ans. There are few major changes happened in the version MVC2. The Microsoft has more concentrated on the HTML Helpers, Validations support, Async controllers etc.
Below are few points which distinguish the ASP.Net MVC 2 different than the previous versions:
a. New HTML Helpers with Strongly Typed
b. Model based validations- This is very useful feature where the validation is done in the Model and will be used throughout the application.
c. Automatic scaffolding feature also got introduces with this version.
d. Asynchronous controller support which enables the multiple tasks to run simultaneously.
e. Html.RenderAction introduced to render the section/part of the page.

5.    Explain MVC Architecture?

Ans. MVC architecture comes with 3 major components-Model, View and Controller.












The main objective of the MVC design pattern is to separate the logic with the UI. So the separation of Concerns is one of the biggest advantages of the MVC design pattern where the UI is separate with business logic.

The user sends the request and the request is taken by the Controller which is heart of the MVC model and takes care of all the actions and events happens in the View. The controller checks whether the request required the Model intervention and if so then call the model to serve the database operations and get the result back. Based on the Model data, the View will be populated. So the Model and View are nothing but the mapping of each other. View is always gets populated based on the Model and not rendered.

6.    What are the new features of ASP.Net MVC 3?
Ans. a. Scaffolding option for the speedup process
       b. Razor engine with the new razor syntax for good readability of the View code.
       c. HTML 5 support
       d. Model based validations
       e. Model Binders to bind the model with View
       f. Action filters
       g. Nuget enabled
       h. Output caching for partial page
       
7.    What are the new features of ASP.Net MVC 4?
Ans. a. Mobile support by adding a new Mobile Project template
       b. ASP.net Web API added for the HTTP requests
       c. Task class support with Async methods
       d. Bundling and Magnification
       e. Login with the social networking websites
       f. Support of Windows Azure SDK
       g. Display modes for the webpage and mobile layout page
       
8.    What are the new features of ASP.Net MVC 5?
Ans. Below are the new features of ASP.Net MVC 5:
a.    One ASP.Net for all type of Web templates
b.    Bootstrap enabled for the ASP.net MVC 5
c.    New Authentication Filter for Controller/Controllers
d.    Attribute Routing
e.    New Scaffolding option
f.     Filter overrides feature
       
9.    Explain ASP.Net MVC application life cycle?
Ans. The application life cycle of ASP.net MVC includes the request, processing, filtering and execution and then finally the response back to the requester. The request first goes to URL routing module (HTTP Module) and there it gets decided that whether this is MVC request and will be handled or not. Now if the request is for MVC application, the URL routing module selects the first route which is satisfying the requested URL. As soon as the first match found for the requested URL, the process for the execution begins with the Controller and Model (if any) and the response sends back to the browser.

10. Advantages of MVC Framework?
Ans. Below are the advantages of MVC framework:
a.           a. Separation of Concerns
b.           b. Light weight
c.           c. No round trip for the layers
d.           d. Decoupling between the layers
e.           e. No dependencies between the Model, View and Controller  
       
11. What do you mean by Separation of Concerns?
Ans. Separation of concerns means all the three components (Model, View and Controller) is not dependent to each other. We can have a single controller which can serve the request and can use any number of Views to populate.

12. Where do we see Separation of Concerns in MVC?
Ans. We can see the separation of concern when we add/remove a View; it will not impact on rest of the application because it’s all depends on when you call, then only it will be used. If there is no call for the View, the application can just keep the view or model with no dependencies.

13. What is Razor View Engine in ASP.Net MVC 3?
Ans. Razor View engine is the new engine which the Microsoft has introduces with the ASP.Net MVC 3. So from ASP.net MVC 3 onward, we can see the ASP.net MVC application will support ASPX as well as Razor view engine. So when we use .aspx to develop our Views, it will use the ASPX engine to execute and when we use the Razor Views (.cshtml or .vbhtml), then it will use the Razor view engine to execute them.

14. Explain the advantages of using routing in ASP.NET MVC?
Ans. There are many advantages of using routing mechanism in ASP.Net MVC like:
a. To keep the URL clean- as in MVC, the default format for the URL is "http://www.myweb.com/Customer/GetCustomer/10". This URL shows that GetCustomer will give the customer details for the id as 10.
b. Discovering the URL by End User- The end user can easily discover the URL details like in above URL, the end user can discover that this URL will give the Customer details for the customer id 10.
c. Avoiding the database ids in URL- with this, we can avoid the id's which are defined in the database.

15. What are the things that are required to specify a route? Which is a better fit, Razor or ASPX?

Ans. RouteConfig.cs is the class used to define the routes. This file is placed under the App_Start folder. The file RouteConfig.cs contains one default route; however the programmer can define other routes as per their requirements.


To specify a route, we need Name and URL of the route. The default URL contains the Controller Name, Action name and the id (if required). By this route, the actual URL gets mapped and if it maps correctly, the view will get displayed, else it shows the 404 error (file not found). 

16. How can you do authentication and authorization in ASP.Net MVC?
Ans. Windows and Form Authentication are available for the Authentication & Authorization in ASP.Net MVC.

17. How to implement Windows authentication for ASP.Net MVC?
Ans.  To Implement the Windows Authentication, it is similar to other application where we can define the authentication mechanism in the config file. In the same way, we can implement the Windows Authentication & Authorization using the below code snippet:



Now, we can retract the particular use to access the controller as below:




We can also restrict the action methods by using the same attribute.

18. How do you implement Forms authentication in ASP.Net MVC? Mention some of the return types of a controller action method.
Ans. The Form Authentication implementation is similar to the ASP.Net form authentication where we need to check the user credentials in each forms to validate the user and then provide the access.

For this, we need to first define the Form Authentication Mode in Web.Config file as:








Now once we define the Form Authentication, we can check the user and set the cookies as:


We also need to include the "using System.Web.Security;" as namespace to get the FormAuthentication class.

The above code is checking the user credentials and then setting it in AuthCookie. Now onwards wherever we want to check for the Form Authentication, we just need to add the [Authorize] attribute to the action methods as:




19. Is ASP.Net MVC suitable for both Windows and web applications?
Ans. No, ASP.Net MVC is primarily made for the Web Applications development. For the Windows Application, MVP is most suitable.

20. What are the benefits of using ASP.Net MVC?
Ans.  The major benefits using ASP.Net MVC are:
a. Separation of concern- separate code behind file
b. Automated testing - testing of the logic with no UI

21. Is MVC different from a three layered architecture?
Ans. Yes, MVC is different than the 3 layered architecture in terms of UI layer(no code behind or separate code behind in MVC), the communication between layers, routing mechanisms etc.
In 3 Layered architecture:
UI <------> Business logic Layer <-------> Data Access Layer
In MVC:
Controller -----> Model
     |                      |

UI (View) <-------

22. What is the latest version of ASP.Net MVC?
Ans.  The current version of ASP.Net MVC is 6. This version of ASP.Net MVC is also called as ASP V-Next which is the common framework to develop MVC, Web Pages, Web API, Signal R applications. Also it can be self hosted and not depends on IIS for hosting. 

23. What is the difference between each version of ASP.Net MVC?
Ans. Below are the features in each of the version in ASP.Net MVC:

ASP.Net MVC 2
a. Async Controller
b. DefaultValueAttribute in Action Method
c. Area concept
d. Bind binary data with the Model binder
e. Model based validations
f. DataAnnotations support
g. Html.ValidationSummary helper method

ASP.Net MVC 3
a. Razor syntax and Razor engine
b. Support for HTML 5
c. Automatic templates available for the Create, List, Edit, View via Scaffolding

ASP.Net MVC 4
a. Web API introduction under ASP.Net MVC
b. Mobile project templates
c. Bundling & Minification
d. Task support for Asynchronous controller
e. Azure SDK
f. Enable login using 3rd party sites like Facebook, Google, and Twitter etc by OAuth & OpenId

ASP.Net MVC 5
a. Attribute based routing
b. One ASP.Net
c. Bootstrap in MVC Templates auto-enabled
d. Authentication Filters
e. Filter Overrides

ASP.Net MVC 6
a. Merging of ASP.Net MVC and Web API
b. Inbuilt DI (Dependency Injection)
c. JSON based project structure (Added JSON)
d. Nuget package based
e. Auto-build by save using Roslyn compiler.
f. Open Source (Runs on Mono, Linux & Mac)

24. What are HTML helpers in MVC?
Ans.  To render HTML controls in View, HTML Helpers are used.
e.g. Html.TextBox ("Address")

25. What is the difference between "Html.TextBox" vs. "HTML.TextBoxFor" in ASP.Net MVC?
Ans. Both the "Html.TextBox" and “HTML.TextBoxFor" will produce the same output but the "HTML.TextBoxFor" is strongly typed while "Html.TextBox" is weakly typed.
e.g. Html.TextBox ("Address") // weakly type
It will give the same output as  
e.g. HTML.TextBoxFor(x => x.Address) // strongly type

26. What is routing in MVC?
Ans. Routing in MVC is used to define the URL structure. It also map the URL to the controller and Action method. For more details, go to the Q.15

27. Where is the route mapping code written?
Ans. RouteConfig.cs is the file where the route is configured. Fore more details, go to the Q.15

28. Can we map multiple URLs to the same action?
Ans. Yes, we can map the multiple URL's to the same action method.

29. How can we navigate from one view to other view using a hyperlink?
Ans. Simply, We can use the ActionLink method and [provide the controller and action method as the parameters. e.g.
Html.ActionLink ("Home”, “Index")

30. How can we restrict MVC actions to be invoked only by GET or POST?

Ans.  We can restrict the actions to be called by GET or POST by decorating the action method by HttpGet or HttpPost as below:









31. How can we maintain sessions in MVC?
Ans. There are various ways to maintain Sessions like-
a. Use Session variables
b. Use Hidden Fields and Html Controls
c. ViewBag - uses Dynamic keyword internally. No need to do casting.
d. ViewData - used to pass data from Controller to View. Casting is required.
e. TempData - between controller to controller or Action to action. It uses Session internally.

32. What is the difference between TempData, ViewData, and ViewBag?
Ans. TempData maintains the data for complete request while ViewData can be used from controller to View. See Q.31

33. What are partial views in ASP.Net MVC?
Ans. Partial View is like User Controls in ASP.Net so they can be used in other views. We can embed as many Partial Views in Main View.

34. How do you create a partial view and consume it in ASP.Net MVC 4?
Ans.  While creating a new view, we can see the option is given to make this view as partial. We need to check the checkbox "Create a Partial View". Once we design and do all the stuff related to filling the data in to the partial view, we can call it using the Html.RenderPartial ("MyPartialView") into our main view.

35. How can we do validations in ASP.Net MVC?
Ans. In ASP.Net MVC, there is no need to do validation in the page (view). We can do the Model based validation which will be done in the Model using the Data Annotations.
To use the Data Annotation, we need to include

using System.ComponentModel.DataAnnotations; namespace in to our model.



36. Can we display all errors in one go? or Validation summery in ASP.Net MVC.
Ans. Html helper class contains a method with the name as ValidationSummary which can be used to show all the errors in one go.
e.g. Html.ValidationSummary()

37. How can we enable data annotation validation on the client side?
Ans.  To enable the Data Annotations at the client side, first we need to include the JQuery validation file and then call the Html.EnableClientValidation() method.

38. What is Razor in MVC?
Ans. Razor is the new engine to parse the MVC code. From ASP.Net MVC 3, Microsoft has introduces this engine. So in ASP.Net MVC 3, there are 2 View Engines- Razor and ASPX

39. Why Razor when we already have ASPX?
Ans. The Razor view Engine is lightweight as compare to the ASPX view engine. Razor engine has quite readable and simple syntax's.

40. How to implement AJAX in MVC
Ans. There are 2 ways to implement AJAX in MVC:
a. By using JQuery
b. By using Ajax Libraries

41. What kind of events can be tracked in AJAX?
Ans. AjaxOption is having the events like OnBegin, OnComplete, OnFailure, OnSuccess etc.

42. What is the difference between ActionResult and ViewResult?
Ans. ActionResult is the base class for all the result types. All the result types are inherited from the ActionResult class. The Derived results types are like -  
ViewResult, JsonResult, FileContentResult etc. 
Whenever we are not sure that what type of result will be returned, we can simply use the ActionResult as the return type.
The ActionResult result type is mainly used for the dynamic view where the result type is not defined. It returns based on the condition.
ViewResult is the derived type and used when the return type of the Action is View. It is specific to the View Type and so can be used only when we are sure that the return type of the action will be only view.

43. What are the different types of results in MVC?
Ans. There are various types of results in ASP.Net MVC. Below are the few:
ViewResult - It is used to renders view type as the result.
PartialViewResult - It is used to renders partial view type as the result.
EmptyResult - To return empty result type
RedirectToRouteResult - To redirect to URL this is determined by the route engine.
JsonResult - to return the JSON format data
JavaScriptResult - To return JavaScript type result
FileContentResult - To return a file type result.

44. What are ActionFilters in MVC?
Ans. If we want to perform some login when the action is executing, we can use ActionFilters to do this.
For example, after the action is completed, we want to do some post processing, we can use ActionFilters.
There are mainly 4 types of action filters available in ASP.net MVC:
a. Authorization filters
b. Action filters
c. Result filters
d. Exception filters
We can also create the ActionFilter by implementing the methods available in IActionFilter interface in the controller class. This interface contains 2 methods- OnActionExecuted and OnActionExecuting
These interface methods take the ActionExecutedContext as the input parameter.

45. Can we create our own custom view engine using MVC?
Ans.  Yes, it is possible to create the Custom View Engine in ASP.Net MVC by implementing IView interface to the View class. 
We need to implement the Render method of the view. Then we need to override the CreateView method in EngineProvider class. Finally we need to add the provider class to the App_Start method. 

46. How to send result back in JSON format in MVC
Ans.  To send the results back to the JSON format, we can use JsonResult as the return type of the action.
In the action method, we can use Json method which will give the Json format of the data.
public JsonResult getEmployee()
{
    Employee objEmployee = new Employee();
    objEmployee.ID = "9001";
    objEmployee.Name = "Ramesh";
    return Json(objEmployee,JsonRequestBehavior.AllowGet);

}
This will give the Json result in the browser.

47. What is Web API?
Ans. Web API is the technology through which we can expose our data over HTTP using ReST principals.
Web API is very light weight and only HTTP is used for the data transfer.

48. But WCF SOAP also does the same thing, so how does Web API differ? With WCF you can implement REST, so why Web API?
Ans.

49. How can we detect that a MVC controller is called by POST or GET?
Ans.

50. What is Bundling and Minification in MVC?
Ans.

51. How does bundling increase performance?
Ans.

52. How do we implement bundling in MVC?
Ans.

53. How can you test bundling in debug mode?
Ans.

54. Explain Minification and how to implement it. How do we implement Minification?
Ans.

55. Explain Areas in MVC?
Ans.

56. Explain the concept of View Model in MVC?
Ans.

57. What kind of logic view model class will have?
Ans.

58. How can we use two(multiple) models in a single view?
Ans.