1. Explain TempData in MVC?
Answer: 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.
2. Why use Html. Partial in MVC?
Answer: 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
3. What do you mean by Separation of Concerns?
Answer: As per Wikipedia ‘the process of breaking a computer program into distinct features that overlap in functionality as little as possible’. MVC design pattern aims to separate content from presentation and data-processing from the content.
4. What are Display Modes in MVC4?
Answer: Display modes use a convention-based approach to allow selecting different views based on the browser making the request. The default view engine first looks for views with names ending with.Mobile.cshtml when the browser’s user-agent indicates a known mobile device. For example, if we have a generic view titled Index.cshtml and a mobile view titled Index.Mobile.cshtml, MVC 4 will automatically use the mobile view when viewed in a mobile browser.
Additionally, we can register your own custom device modes that will be based on your own custom criteria — all in just one code statement. For example, to register a WinPhone device mode that would serve views ending with.WinPhone.cshtml to Windows Phone devices, you’d use the following code in the Application_Start method of your Global.asax:
5. What are the advantages of MVC
Answer: A main advantage of MVC is a 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 to 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 a unit test. We can write won a test case.
The latest version of MVC Support default responsive web site and mobile templates.
6. What is the difference between ActionResult and ViewResult?
Answer: ActionResult is an abstract class while ViewResult derives from the ActionResult class.
ActionResult has several derived classes like ViewResult, JsonResult, FileStreamResult, and so on.
ActionResult can be used to exploit polymorphism and dynamism. So if you are returning different types of views dynamically, ActionResult is the best thing. For example in the below code snippet, you can see we have a simple action called DynamicView. Depending on the flag (IsHtmlView) it will either return a ViewResult or JsonResult.
7. What are Route Constraints in MVC?
Answer: This is very necessary for when we want to add a specific constraint to our URL. So, we want to set some constraint string after our hostname. Fine, let’s see how to implement it.
It’s very simple to implement, just open the RouteConfig.cs file and you will find the routing definition in that. And modify the routing entry as in the following. We will see that we have added “ABC” before.
8. What are the Folders in MVC application solutions?
Answer: 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 are 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 contain methods known as “Actions” which response to the user action accordingly.
Views: These are simple pages which use 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.
9. What do you mean MVC?
Answer: MVC is a framework pattern that splits an application’s implementation logic into
three-component roles: models, views, and controllers.
Model: The business entity on which the overall application operates. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be encapsulated by the Model.
View: The user interface that renders the model into a form of interaction.
Controller: Handles a request from a View and updates the model that results in a change of the Model’s state.
To implement MVC in .NET we need mainly three classes (View, Controller, and the Model).
10. Where do we see Separation of Concerns in MVC?
Answer: Between the data-processing (Model) and the rest of the application.
When we talk about Views and Controllers, their ownership itself explains separation. The views are just the presentation form of an application, it does not have to know specifically about the requests coming from the controller. The Model is independent of View and Controllers, it only holds business entities that can be passed to any View by the controller as required for exposing them to the end-user. The controller is independent of Views and Models, its sole purpose is to handle requests and pass it on as per the routes defined and as per the need of rendering views. Thus our business entities (model), business logic (controllers) and presentation logic (views) lie in logical/physical layers independent of each other.
11.Differences between Razor and ASPX View Engine in MVC?
Answer: Razor View Engine VS ASPX View Engine
Razor View Engine ASPX View Engine (Webform view engine)
The namespace used by the Razor View Engine is System.Web.Razor The namespace used by the ASPX View Engine is System.Web.MVC.WebFormViewEngine
The file extensions used by the Razor View Engine are different from a web form view engine. It uses cshtml with C# and vbhtml with vb for views, partial view, templates, and layout pages. The file extensions used by the Web Form View Engines are like ASP.Net web forms. It uses the ASPX extension to view the aspect extension for partial views or User Controls or templates and master extensions for layout/master pages.
The Razor View Engine is an advanced view engine that was introduced with MVC 3.0. This is not a new language but it is markup. A webform view engine is the default view engine and available from the beginning of MVC
Razor has a syntax that is very compact and helps us to reduce typing. The webform view engine has a syntax that is the same as an ASP.Net forms application.
The Razor View Engine uses @ to render server-side content. The ASPX/webform view engine uses to render server-side content.
By default all text from an @ expression is HTML encoded. There is a different syntax (“<%: %>”) to make text HTML encoded.
Razor does not require the code block to be closed, the Razor View Engine parses itself and it is able to decide at runtime which is a content element and which is a code element. A webform view engine requires the code block to be closed properly otherwise it throws a runtime exception. (Company)
The Razor View Engine prevents Cross-Site Scripting (XSS) attacks by encoding the script or HTML tags before rendering to the view. A webform View engine does not prevent Cross-Site Scripting (XSS) attack.
The Razor Engine supports Test Driven Development (TDD). Web Form view engine does not support Test Driven Development (TDD) because it depends on the System.Web.UI.Page class to make the testing complex.
Razor uses for multiline comments. The ASPX View Engine uses “for markup and for C# code.
There are only three transition characters with the Razor View Engine. There are only three transition characters with the Razor View Engine.
The Razor View Engine is a bit slower than the ASPX View Engine.
12. What are the possible Razor view extensions?
Answer: 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.
13. What is Area in MVC?
Answer: Area is used to store the details of the modules of our project. This is really helpful for big applications, where controllers, views, and models are all in the main controller, view and model folders and it is very difficult to manage.
14. What is the difference between ViewBag and ViewData in MVC?
Answer: ViewBag is a wrapper around ViewData, which allows creating dynamic properties. Advantage of view bag over viewdata will be –
In ViewBag no need to typecast the objects as in ViewData.
ViewBag will take advantage of the 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.
15. What are the Filters?
Answer: Sometimes we want to execute some logic either before the execution of the action method or after the execution of the action method. We can use Action Filter for such kind of scenario. Filters define logic which is executed before or after the execution of the action method. Action Filters are attributes which we can apply to the action methods.
Following are the MVC Filters:
- Authorization filter
- Action filter
- Result filter
- Exception filter
For example, to apply to authorize filter we apply the attribute as:
2. public ActionResult Index()
3. return View();
16. What is a View Engine?
Answer: View Engines are responsible for generating the HTML from the views. Views contain HTML and source code in some programming language such as C#. View Engine generates HTML from the view which is returned to the browser and rendered. Two main View Engines are WebForms and Razor, each has its own syntax.
17. Which assembly contains the ASP.NET MVC classes and interfaces?
Answer: The main functionality of ASP.NET MVC is defined in the System.Web.MVC assembly. It contains the classes and interfaces which supports the MVC functionality. System.Web.MVC is the namespace which contains the classes used by the MVC application.
18: What is MVC (Model view controller)?
Answer: Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representation of information from the way that information is presented to or accepted from the user.
MVC is a framework for building web applications using an MVC (Model View Controller) design:
The Model represents the application core (for instance a list of database records).
The View displays the data (the database records).
The Controller handles the input (to the database records).
The MVC model defines web applications with 3 logic layers:
- The business layer (Model logic)
- The display layer (View logic)
- The input control (Controller logic)
- The Model is the part of the application that handles the logic for the application data.
- Often model objects retrieve data (and store data) from a database.
- The View is the part of the application that handles the display of the data.
- Most often the views are created from the model data.
The Controller is the part of the application that handles user interaction.
- Typically controllers read data from a view, control user input, and send input data to the model.
- The MVC separation helps you manage complex applications because you can focus on one aspect a time.
- For example, you can focus on the view without depending on the business logic. It also makes it easier to test an application.
- The MVC separation also simplifies group development. Different developers can work on the view, the controller logic, and the business logic in parallel.
19. What are Action Filters in MVC?
Answer: 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. The attribute which can be attached to classes, methods, properties, and fields.
20. What is Razor in MVC?
Answer: 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.
21. Explain the concept of MVC Scaffolding?
Answer: 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.
22. What is Output Caching in MVC?
Answer: The main purpose of using Output Caching is to dramatically improve the performance of an ASP.NET MVC Application. It enables us to cache the content returned by any controller method so that the same content does not need to be generated each time the same controller method is invoked. Output Caching has huge advantages, such as it reduces server round trips, reduces database server round trips, reduces network traffic, etc.
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 anyone.
23. What is ViewStart?
Answer: Razor View Engine introduced a new layout named _ViewStart which is applied to all view automatically. Razor View Engine firstly executes the _ViewStart and then start rendering the other view and merges them.
24. Explain RenderSection in MVC?
Answer: 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.. (asp dot net MVC online training)
25. What is MVC?
Answer: MVC is a pattern which is used to split the application’s implementation logic into three components: models, views, and controllers.
26. Can you explain the page life cycle of MVC?
Answer: Below is the process followed in the sequence –
Instantiate and execute controller
Locate and invoke controller action
Instantiate and render view.
27. Explain JSON Binding?
28. Can a view be shared across multiple controllers? If Yes, How we can do that?
Answer: Yes, we can share a view across multiple controllers. We can put the view in the “Shared” folder. When we create a new 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.
29. How we can handle the exception at controller level in MVC?
Answer: Exception Handling is made simple in MVC and it can be done by just overriding “OnException” and set the result property of the filter context object (as shown below) to the view detail, which is to be returned in case of exception.
30. What is Representational State Transfer (REST) mean?
Answer: REST is an architectural style which uses HTTP protocol methods like getting, POST, PUT, and DELETE to access the data. MVC works in this style. In MVC 4 there is support for Web API which uses to build the service using HTTP verbs.
31. What are the differences between Partial View and Display Template and Edit Templates in MVC?
Answer: Display Templates – These are model-centric. Meaning it depends on the properties of the view model used. It uses the convention that will only display like divs or labels.
Edit Templates – These are also model-centric but will have editable controls like Textboxes. Partial View – These are view centric. These will differ from templates by the way they render the properties (Id’s) Eg: CategoryViewModel has Product class property then it will be rendered as Model.Product.ProductName but in case of templates if we CategoryViewModel has List then @Html.DisplayFor(m => m.Products) works and it renders the template for each item of this list.
32. Why use ASP.Net MVC
Answer: The strength of MVC (i.e. ASP.Net MVC) is listed below, that will answer this question
MVC reduces the dependency between the components; this makes your code more testable.
MVC does not recommend the use of server controls, hence the processing time required to generate HTML response is drastically reduced.
33. What are Bundling and Minification?
Answer: Bundling and Minification is used for improving the performance of the application. Bundling reduces the number of HTTP requests made to the server by combining several files into a single bundle. Minification reduces the size of the individual files by removing unnecessary characters.
34. List out different return types of a controller action method?
Answer: There is a total of nine return types we can use to return results from the controller to view.
ViewResult (View): This return type is used to return a webpage from an action method.
PartialviewResult (Partial view): 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.
JSON result (JSON): This return type is used when we want to return a JSON message.
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.
35. What is Route in MVC? What is Default Route in MVC?
Answer: 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. (Interview Questions all)
36. What is Partial View in MVC?
Answer: A partial view is a chunk of HTML that can be safely inserted into an existing DOM. Most commonly, partial views are used to componentize Razor views and make them easier to build and update. Partial views can also be returned directly from controller methods. In this case, the browser still receives text/Html content but not necessarily HTML content that makes up an entire page. As a result, if a URL that returns a partial view is directly invoked from the address bar of a browser, an incomplete page may be displayed. This may be something like a page that misses title, script and style sheets. However, when the same URL is invoked via a script, and the response is used to insert HTML within the existing DOM, then the net effect for the end-user may be much better and nicer.
Partial view is a reusable view (like a user control) which can be embedded inside another view. For example, let’s say all the pages of your site have a standard structure with left menu, header, and footer as in the following image,
37. Explain Areas in MVC?
Answer: 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.
Benefits of Area in MVC
Allows us to organize models, views, and controllers into separate functional sections of the application, such as administration, billing, customer support and much more.
Easy to integrate with other Areas created by another.
Easy for unit testing.
38. How to change the action name in MVC?
Answer: “ActionName” attribute can be used for changing the action name. Below is the sample code snippet to demonstrate more
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.
39. What is Html?RenderPartial?
Answer: 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
40. How to create a Controller in MVC
Answer: Create a simple class and extend it from the Controller class. The bare minimum requirement for a class to become a controller is to inherit it from ControllerBase is the class that is required to inherit to create the controller but Controller class inherits from ControllerBase.
41. How to access a view on the server
Answer: The browser generates the request in which the information like Controller name, Action Name and Parameters are provided when the server receives this URL it resolves the Name of Controller and Action, after that it calls the specified action with provided parameters. Action normally does some processing and returns the ViewResult by specifying the view name (blank name searches according to naming conventions).
42. What are HTML helpers in MVC?
Answer: HTML helpers help you to render HTML controls in the view. For instance, if you want to display an HTML textbox on the view, below is the HTML helper code.
43. What are AJAX Helpers in MVC?
Answer: AJAX Helpers are used to creating AJAX-enabled elements like as Ajax enabled forms and links which performs the request asynchronously and these are extension methods of AJAXHelper class which exists in namespace – System.Web.MVC.
44. Can you explain RenderBody and RenderPage in MVC?
Answer: 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 the Layout page.
45. Explain the methods used to render the views in MVC?
Answer: Below are the methods used to render the views from the action –
View() – To return the view from the action.
PartialView() – To return the partial view from the action.
RedirectToAction() – To Redirect to different activities which can be in the same controller or in a 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 routing table has been matched
46. What are the subtypes of ActionResult?
Answer: Action Result is used to represent the action method result. Below are the subtypes of ActionResult –
- View Result
47. What are Validation Annotations?
Answer: Data annotations are attributes which can be found in the “System.Component Model.Data Annotations” 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.
48. How do you implement Forms authentication in MVC?
Answer: Authentication is giving access to the user for a specific service by verifying his/her identity using his/her credentials like username and password or email and password. It assures that the correct user is authenticated or logged in for a specific service and the right service has been provided to the specific user based on their role that is nothing but authorization.
ASP.NET forms authentication occurs after IIS authentication is completed. You can configure forms authentication by using forms element within the web.config file of your application. The default attribute values for forms authentication are shown below: The Forms Authentication class creates the authentication cookie automatically when SetAuthCookie() or RedirectFromLoginPage() methods are called. The value of the authentication cookie contains a string representation of the encrypted and signed Forms Authentication Ticket object.
49. What is Razor View Engine in MVC?
Answer: ASP.NET MVC has always supported the concept of “view engines” that are the pluggable modules that implement various template syntax options. The “default” view engine for ASP.NET MVC uses the same .aspx/.ascx/.master file templates as ASP.NET WebForms. In this article, I go through the Razor View Engine to create a view of an application. “Razor” was in development beginning in June 2010 and was released for Microsoft Visual Studio in January 2011.
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.
50. What is Scaffolding in MVC?
Answer: 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.
All MVC Interview Questions
.Net Mvc Training VideosDuration: 30+ Hours | Version: 6.0
- Experienced Faculty
- Real-time Scenarios
- Free Bundle Access
- Course Future Updates
- Sample CV/Resume
- Interview Q&A
- Complimentary Materials