1. Tell me where is the route mapping code written?
The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax" application start event.
2. Tell me is it possible to share a view across multiple controllers?
Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.
3. Tell us what is Route in MVC? What is Default Route in MVC?
A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as a .aspx file in a Web Forms application. A handler can also be a class that processes the request, such as a controller in an MVC application. To define a route, you create an instance of the Route class by specifying the URL pattern, the handler, and optionally a name for the route.
You add the route to the application by adding the Route object to the static Routes property of the RouteTable class. The Routesproperty is a RouteCollection object that stores all the routes for the application.
You typically do not have to write code to add routes in an MVC application. Visual Studio project templates for MVC include preconfigured URL routes. These are defined in the Mvc Application class, which is defined in the Global.asax file.
4. Explain me what is Areas in MVC?
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:
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.
5. Tell me what is the greatest advantage of using asp.net mvc over asp.net webforms?
It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.
6. Tell me what are the Folders in MVC application solutions?
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.
7. Tell us what are Action Filters in MVC?
Action Filters are additional attributes that can be applied to either a controller section or the entire controller to modify the way in which action is executed. These attributes are special .NET classes derived from System.Attribute which can be attached to classes, methods, properties and fields.
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.)
8. Tell me what are HTML helpers in MVC?
HTML helpers help you to render HTML controls in the view. For instance if you want to display a HTML textbox on the view , below is the HTML helper code.
<%= Html.TextBox("FirstName") %>
For checkbox below is the HTML helper code. In this way we have HTML helper methods for every HTML control that exists.
<%= Html.CheckBox("Yes") %>
9. Tell us what is Bundling and Minification in MVC?
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.
10. Tell us what is GET and POST Actions Types?
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 ] )
Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application.
Yes, all the features in an asp.net MVC application are interface based and hence mocking is much easier. So, we don't have to run the controllers in an ASP.NET process for unit testing.
13. What is Dependency Resolution?
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.
14. Do you know what is Razor in MVC?
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.
15. Tell us what are the advantages of MVC?
☛ A main advantage of MVC is separation of concern. Separation of concern means we divide the application Model, Control and View.
☛ We can easily maintain our application because of separation of concern.
☛ In the same time we can split many developers work at a time. It will not affects one developer work to another developer work.
☛ It supports TTD (test-driven development). We can create an application with unit test. We can write won test case.
☛ Latest version of MVC Support default responsive web site and mobile templates.
16. Tell us what is the role of a controller in an MVC application?
The controller responds to user interactions, with the application, by selecting the action method to execute and alse selecting the view to render.
17. Explain me what is Validation Summary in MVC?
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.
18. Explain me what is the significance of NonActionAttribute?
In general, all public methods of a controller class are treated as action methods. If you want prevent this default behaviour, just decorate the public method with NonActionAttribute.
19. Explain me the meaning of Unobtrusive JavaScript?
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.
20. Please explain what does Model, View and Controller represent in an MVC application?
Model: Model represents the application data domain. In short the applications business logic is contained with in the model.
View: Views represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI.
Controller: Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface. The user input logic is contained with in the controller.
21. Tell us what is Output Caching in MVC?
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
22. Do you know what is the difference between View and Partial View?
View:
☛ It contains the layout page.
☛ Before any view is rendered, viewstart page is rendered.
☛ View might have markup tags like body, html, head, title, meta etc.
☛ 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.
23. Tell me different return types of a controller action method?
There are total nine return types we can use to return results from controller to view.
☛ ViewResult (View): This return type is used to return a webpage from an action method.
☛ PartialviewResult (Partialview): This return type is used to send a part of a view which will be rendered in another view.
☛ RedirectResult (Redirect): This return type is used to redirect to any other controller and action method depending on the URL.
☛ RedirectToRouteResult (RedirectToAction, RedirectToRoute): This return type is used when we want to redirect to any other action method.
☛ ContentResult (Content): This return type is used to return HTTP content type like text/plain as the result of the action.
☛ jsonResult (json): This return type is used when we want to return a JSON message.
☛ javascriptResult (javascript): This return type is used to return JavaScript code that will run in browser.
☛ FileResult (File): This return type is used to send binary output in response.
☛ EmptyResult: This return type is used to return nothing (void) in the result.
24. Explain me what is the difference between ActionResult and ViewResult?
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
☰ }
25. Tell us what is ViewStart?
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>
26. Tell me how can we do exception handling in MVC?
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;
27. Tell us what are the advantages of ASP.NET MVC?
☛ 1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
☛ 2. Complex applications can be easily managed
☛ 3. Seperation of concerns. Different aspects of the application can be divided into Model, View and Controller.
☛ 4. ASP.NET MVC views are light weight, as they donot use viewstate.
28. Tell me a few different return types of a controller action method?
The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.
☛ 1. ViewResult
☛ 2. JavaScriptResult
☛ 3. RedirectResult
☛ 4. ContentResult
☛ 5. JsonResult
29. What is RenderSection in MVC?
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.
<div id="body">
@RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
@RenderBody()
</section>
</div>
30. What is the concept of MVC Scaffolding?
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.
31. Explain me what is the difference between Temp data, View, and View Bag?
In ASP.NET MVC there are three ways to pass/store data between the controllers and views.
ViewData
☛ ViewData is used to pass data from controller to view.
☛ It is derived from ViewDataDictionary class.
☛ It is available for the current request only.
☛ Requires typecasting for complex data type and checks for null values to avoid error.
☛ If redirection occurs, then its value becomes null.
ViewBag
☛ ViewBag is also used to pass data from the controller to the respective view.
☛ ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
☛ It is also available for the current request only.
☛ If redirection occurs, then its value becomes null.
☛ Doesn't require typecasting for complex data type.
TempData
☛ TempData is derived from TempDataDictionary class
☛ TempData is used to pass data from the current request to the next request
☛ It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
☛ It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages
32. Explain me what is the difference between “HTML.TextBox” and “HTML.TextBoxFor”?
Both provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn't. Below is a simple HTML code which just creates a simple textbox with “FirstName” as name.
Html.TextBox("FirstName ")
Below is “Html.TextBoxFor” code which creates HTML textbox using the property name ‘FirstName” from object “m”.
Html.TextBoxFor(m => m.CustomerCode)
In the same way, we have for other HTML controls like for checkbox we have “Html.CheckBox” and “Html.CheckBoxFor”.
33. Explain me what is MVC Application Life Cycle?
Any web application has two main execution steps first understanding the request and depending on the type of the request sending out the appropriate response. MVC application life cycle is not different it has two main phases first creating the request object and second sending our response to the browser.
Creating the request object: -The request object creation has four major steps. Below is the detail explanation.
☛ Step 1 Fill route: MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.
☛ Step 2 Fetch route: Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.
☛ Step 3 Request context created: The “RouteData” object is used to create the “RequestContext” object.
☛ Step 4 Controller instance created: This request object is sent to “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.
☛ Step 5 Creating Response object: This phase has two steps executing the action and finally sending the response as a result to the view.
34. Tell us what is the significance of NonActionAttribute?
ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file.
35. Tell us where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax