MVC interview questions

MVC interview questions | Freshers & Experienced

  • Ketan Chauhan
  • 06th Mar, 2021
  • 665 Followers

Key Features of Mvc

Below are few major features of Mvc

Attribute Routing

Frictionless testability. Highly testable

extensible

pluggable framework

Bootstrap

MVC interview questions

Q1. What MVC stands for?

MVC stands for Model-View-Controller. In an application, the three parts, that is, the model, view and controller are interconnected and helps to create the pattern and the design of the application. It separates the data, logic, and presentation of an application into independent components. The MVC model is a representation of the data application. For example, if you have a shopping site, a cart will represent the state of the shopping of the user. The model is the data file or simply an object that is used by the program. The view is the representation of the data contained inside a model visually. And, the controller handles the input of the user, update the model state and make the changes that are caused due to the action of the user.

asp.net MVC architecture diagram

Q2. Explain how routing works in MVC Pattern?

All the requests to the MVC are first received by a routing module object. This routing module object is one type of module for the HTTP script. The module next parses the requests. The request encloses all the routes registered in the Global.aspx file under the event of Application_start.

URLRoutingModule then searches the entire route that is present in the URL and matches with the exact one. Route handler is then retrieved for that route when a perfect match is found. Route Handler then searches for the HTTP Handler for the current request.

Q3. How does the 'page lifecycle' of ASP.Net MVC works?

The page lifecycle of ASP.Net MVC works in the following way:

  • In MVC application all the routing requests enter a special class named controller. The Controller is accountable for creating a response and transferring the content back to the web browser.
  • URL Routing Module captures all the requests
  • A request is always intercepted by an UrlRoutingModule via the HTTP module.
  • MVCHandler is inherited from HTTPAsyncHandler. When the handler performs, it starts the BeginProcessRequests of the AsyncHandler.
  • The Controller Performed: Next, the controller class creates some parameters from the requests through the ControllerActionInvoker.
  • Finally, the Render View Method finishes off
  • The controller finally performs the RenderView Method and is called on the ViewPage.

Q4. What is Razor View Engine?

Razor is a programming markup syntax used to create server-side code and HTML code in all the dynamic web pages of an application. It is created using VB.NET or C# programming languages. Razor is an engine for templates and is used inside an MVC application to create an HTML script. The syntax is compact in nature and is simple to implement.

Here are a few of the Razor Syntax Rules that you can write for C#:

  • You always need to enclose it in @{ ... }
  • You need to end the statements with Semicolon ";"
  • The files that you use should have an extension of .cshtml.
  • Try to declare the variables with var keyword
  • Case sensitive is C# code.
  • The inline expressions should always start with @

Q5. What are Actions in ASP.Net MVC?

Actions in ASP.Net MVC are programmed to execute requests and generate a valuable response in ActionResult form. One-to-one mapping with end-users and making interaction with them is the main feature of ASP.NET MVC Actions.

There are different ActionResult classes and their associated behavior. They are:

  • ContentResult that returns a string
  • FilePathResult, FileStreamResult, and FileContentResult that returns the content of the file
  • EmptyResult that returns nothing
  • JsonResult that returns JSON data
  • HttpUnauthorizedResult that returns a 403-status code
  • ViewResult which received the response of a vie engine
  • JavaScriptResult that returns the script for the execution
  • RedirectToResult that redirects to a specific URL
  • RedirectToRouteResult and PartialViewResult that redirects to the different controller action

Q6. What is Attribute Routing? How to enable it?

The MVC 5 now supports attribute routing. You can add a route to the routing table using attributes in such an order that the route definitions are close to their corresponding actions. Moreover, attribute routing enables you with more control over your web application's URLs.

The earlier style of routing, called convention-based routing, is still fully supported. In fact, you can combine both techniques in the same project.

You can enable Attribute Routing by adding MapMvcAttributeRoutes in the RouteCollection or RouteConfig segment of the application. Here is a small code snippet:

public class RouteConfig
{
    public static void RegisRoute(RouteCollection x)
    {
        x.IgnoreRoute("{resource}.axd/{*information}");
 
        x.MapMvcAttributeRoutes();
    }
}

Q7. List few the advantages of MVC?

Some of the biggest advantages of MVC are:

  • MVC allows full control over the HTML
  • Offers clear SoC (Separation of Concerns)
  • Full Implementation of TDD (Test Driven Development)
  • Simple integration with the framework of JavaScript
  • MVC takes care of the restful URL that assisting in the SEO
  • Absence of any PostBack or ViewState Events

Q8. What is the role of components Presentation in MVC?

In MVC, components Presentation is the visual representation of a specific abstraction within the application.

The roles of the main three components of MVC is model, view, and controller:

  • Model: The 1st component is the model and it comprises of the code to link to the database or to the Java Beans. It mainly consists of one or more classes that provide the infrastructure which is needed to support the views.
  • View: View has many GUI components and the values which you get through querying are viewed and displayed by this model. Moreover, updates to the controller are also performed by the view.
  • Controller: The Controller mainly controls and updates the model through which it views as required. It invokes the model to perform all sorts of updates. Moreover, it carries forward from maps to the commands which you need to send to the model

Q9. How do we implement Ajax in MVC?

Ajax is a shorthand form for Asynchronous XML and JavaScript. The MVC consists of inbuilt unobtrusive Ajax. To implement the unobtrusive Ajax in MVC, you have to open the Web.Config file and put the UnobtrusiveJavaScriptEnabled element inside the Application settings section by using a particular code. Next, open the common Layout.cshtml file placed under a shared or views folder and add mentions to the jQuery libraries.

Q10. What is the difference between Partial View and View?

View in MVC is the generalized display of a webpage that appears in the results and includes markup tags like head, Meta, body, HTML, etc. Before View, ViewStart Page is rendered. It is the highest level of the container. The view is more like a form for web content and is completely lightweight.

Partial view in MVC is a small portion of content that can be used multiple times on a page or in a variety of pages. The partial view is more like a user control and does not contain a webpage layout. We cannot enter common code for partial view in the ViewStart.cshtml.page. The partial view can be passed onto the RenderPartial method.

Q11. What is ViewData?

ViewData is a type of dictionary that contains Key-value pairs and in which each key is a string. Data is transferred from the controller to View via ViewData. This is a one-way process of transferring the data. Moreover, the Data cannot be pushed back to Controller and is only valid for the recent request. ViewData is a mechanism for communication within the server and is obtained from ViewDataDictionary. It should be typecast right before use.

Q12. What is strongly typed view in MVC?

Through strongly typed views, specific objects are rendered without using generalized ViewData. It is inherited from the ViewPage like ViewPage where T is the model type. Intellisense, automatic scaffolding and compile type checking of time are some of the advantages of a Strongly Typed View in MVC. Model properties can be accessed and render controls via this type of view.

In a strongly-typed view, a specific class model objects are designed. It binds with the matching model objects and produces a scaffolding view.

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

The differences between ViewBag and ViewData are:

ViewData is a dictionary accessed from the ViewDataDictionary. It uses strings as keys. Viewdata needs typecasting for the data which are complex in nature and also correct the null values to avoid errors. ViewData is used to transfer data from the Controller to the View and cannot be reversed.

ViewBag is a dynamic attribute that is advantageous for C# 4.0. ViewBag does not require complex data typecasting. It can access any number of values dynamically and add any additional fields instead of converting the data to a strongly typed View. In other words, ViewBag acts as a wrapper around ViewData.

Q14. What are AJAX Helpers in MVC?

AJAX helpers are employed to create AJAX elements like Ajax-enabled links or forms that perform requests in an asynchronous way. Ajax Helpers are the extensions of the AJAXHelper class which are present in the System.Web.MVC namespace. It is used to generate anchor and form tags that direct towards the action method of the controller. There are various options like URL, OnBegin, OnSuccess, LoadingElementId, UpdateTargetId and many more for proper configuration of the Ajax Helpers.

Q15. What is Layout in MVC?

Layouts in MVC use a common template to inherit the feel and look of the pages of the template in the web applications. The layout contains the same code as the master page of the Web application in ASP.NET.

For example, an application interface contains the left and right menu bar, Header, and footer on a page. The above-mentioned section remains the same for every page due to layout in MVC, only the other portion changes. Due to layout coding has become error-free, and is very quick and easy to maintain.

Q16. What is dependency injection in MVC?

Dependency Injection is a design pattern that removes the responsibility of the dependency creation derived from a class. This results in a loosely coupled designer system. Through dependency injection, Inversion of Control (IoC) is implemented by injecting the IoC inside a class via some outside source.

The inserted dependencies are either received as parameters of the constructor or assigned to the properties of the designed class. Dependency injection also drives a dependency to the dependent object (from DAL to Domain layer). DI prevents instantiation of the code from the layer of data accessing segment into the View or Business layer. There are three types of classes involved in the Dependency Injection. They are:

  • Client Class that is dependent on the service class
  • Service Class offers service to the client class
  • Injector class injects the object from the service class inside the client class

Q17. What is bundling in MVC?

Bundling loads a bunch of files that are static in nature from the server into one request of HTTP. Through bundling, you can load an innumerable JavaScript file. It helps to minimize the loading time of a webpage by reducing the number and size of the files requested.

Three types of bundle classes are present inside the System.Web.Optimization of the MVC framework. They are:

  • ScriptBundle that reduces the number of JavaScript from multiple or single script files.
  • DynamicFolderBundle is a bundle created from the folder of ASP.NET containing files of the same nature.
  • StyleBundle decreases the CSS from multiple or single sheet files.

Q18. What is HTML helpers in MVC?

HTMLHelper class in ASP.NET contains various methods that assist to create a control for HTML programmatically. The helper returns the results in the form of a string and produces the final HTML at the runtime. The helper class generates UI and cannot be applied in the models of controllers. There are three types of HTMLHelper methods. They are:

  • Createinputs: As evident from the name, it produces inputs for the buttons and text boxes.
  • Createforms: Produces tags for the forms that post back in response to our action or action from a different controller
  • Createlinks: It generates links based on the information present in the routing table.

Q19. Explain data annotation in MVC?

Data Annotations (DA) are certain validations inside a model to check the validity of the input generated by the user. DA is very easy to use than the normal ASP.NET annotations. The different types of Data Annotations used in MVC are:

  • Required indicates that the value is compulsory and cannot be omitted.
  • Range set a range in between two numbers.
  • DataType indicates the model data type.
  • StringLength specifies minimum and maximum property length.
  • MaxLength indicates the maximum property length.
  • DisplayLength inserts the name of the property that is displayed on the view.
  • Bind indicates which field is to be included or excluded for the binding of the model.
  • RegularExpression place a regex property pattern.
  • DisplayFormat set the date according to the format specified by the attribute.

Q20. What is TempData in MVC?

TempData in MVC stores temporary data that can be applied in the subsequent request. It is useful for transferring non-sensitive data from one to another action method of the controllers. It is a type of dictionary that originated from TempDataDictionary.

The values in the TempData are retained through redirection and use the session to save the data. The data must be typecast before applying and can store only 1-time messages like validation or error messages. Always remember to insert TempData.Keep() to put all the TempData values in third requests.

//example 
TempData[“name”] = “TempData”; // store data in TempData 
string name = TempData[“name”].toString(); //retrieve data from TempData 

Q21. Explain the mvc application life cycle?

In the MVC lifecycle, first, the request to the MVC application is sent from the client browser. The IIS determines that the request needs to be processed by the ASP.net application. The requested URL is first routed to the MVC application by the MvcRouteHandler. After intercepting the request, the HttpContextWrapper object is created. Then, the MVC handler executes the BeginProcessRequest method call. When the method is called, an MVC controller is created from a ControllerFactory.

After creating the controller, the MVC handler invokes the execute method on the controller. Then the controller executes the necessary method based on the request. ViewResult locates the corresponding view and invokes the render method. After rendering the result view, it is displayed to the client browser.

Q22. What is MvcHandler in ASP.NET?

The handler in the MVC is responsible for handling the request from the user browser and producing the appropriate response for the specific content. The MVC handler class doesn’t produce the response by itself.

It uses the ControllerBuilder object for creating a Controller from the ControllerFactory and calls the Execute method in the controller. The Execute method has the responsibility to find and call the appropriate action for the request. Then the action is wrapped to return it in the HTTP response as a result by the handler class.

Q23. What is Output Caching in MVC?

The output cache in the MVC is used to cache the content returned by the controller. So, every time the controller method is invoked, it doesn’t need to regenerate the content as it is saved in the output cache. Output cache improves the performance of the ASP.net MVC application significantly. This cache should be used for content that is accessed frequently and the same cache should not be used for different users.

The output cache improves the application performance by reducing the network traffic, server round trips, and database round trips.

Q24. Enlist Different Types of Caching in asp.net MVC?

Caching provides the user with a way of storing the frequently accessed data to improve the performance of the application.

In ASP.net MVC, there are Three ways of caching content.

  1. Static content caching

    Static content is a common form of data in the web application. Static content doesn’t change dynamically, it remains the same throughout the life of the application like the CSS or HTML content. These contents are heavy to load from the server each time the application is called. So, it should be cached to improve performance. Static content caching can be configured in the Web. Config file.

  2. Caching using OutputCache Attribute

    Here, the page response or the content from the action method is cached by using the OutputCache attribute. This attribute can be used with a controller or activity level to improve the performance of the application.

  3. Shared data Caching

    The data that needs to be shared between multiple action methods can be cached using the HttpContext.Cache. It can be used to get or set the data in the cache to improve the performance.

Q25. What are Action Filters in MVC?

Action Filter in MVC is a type of filter that is executed before and after the execution of the action method. OutputCache is an example of a built-in action filter in MVC.

These filters can be applied to an individual action method or the whole controller.

//example for an action filter – OutputCache 
[OutputCache(Duration=10)] public ActionResult Index() { return View(); }

Note:- In the above example, the output is cached for 10 seconds.

MVC Gives the user an option to create a custom action filter. It can be implemented by using the IActionFilter interface and the FilterAttribute class, Or by using the ActionFilterAttribute abstract class.

Q26. What is default route in mvc?

The ASP.net MVC application has a default route table tha contains the single default route. This default route maps the first segment of the URL to the controller Name. Then, the second segment of the URL to the controller action, and finally, the last segment of the URL to a parameter called id.

If the controller is not specified, then that parameter defaults to the value Home. If the controller action is not specified, then that parameter defaults to Index. If the parameter is not specified the defaults to empty string.

Q27. List different types of filter available in MVC?

Filters are used to implement logic at various levels in the application like logging, authorization, or caching.

There are five filters available in the ASP.net MVC.

  • Authentication Filter

It runs first before another type of filter. It is used for the authentication purpose of individual users. It is implemented using the IAuthenticationFilter interface.

  • Authorization Filter

It is used to check the authorization for user access. AuthorizeAttribute is an example of authorization filter. It implements the IAuthorizationFilter interface.

  • Action Filter

It is used to call before or after an execution of action methods to modify data, etc. It is implemented from the IAction interface.

  • Result Filter

It is executed before or after a view result is executed to modify it. It implements the IResultFilter Interface. OutputCacheAttribute is an example of this type.

  • Exception Filter

These are used to handle the exceptions thrown. It implements the IExceptionFilter Interface. HandleErrorAttribute class is an example of this type.

Q28. Enlist some important namespaces used in Asp.net MVC?

A namespace can be defined as a container of Class, Interface, Structures, Delegations, Enumerations, etc. Using namespace, it is possible to use the same class name without collision.

Some of the important namespace in the ASP.NET MVC is,

  • System.Web.Mvc

It includes controllers, libraries, actions, views, and models to create web applications. It follows the MVC pattern.

  • System.Web.Mvc.Ajax

It is used in web applications. It has classes that supports AJAX scripts, and AJAX related settings and options.

  • System.Web.Mvc.Async

It has classes and interface that supports the development of asynchronous actions in web applications.

  • System.Web.Mvc.Html

It includes classes for forms, controls, links, views, and validations to support the helper application. It follows the MVC pattern.

Q29. How to bind an object from controller to view in mvc?

The binding object is a way of passing data from the controller to the view using the controller.

To pass the data,

Create your model class and controller first. Use the return statement to return the object from your model class. Then import the binding object of the model class at the top of your Index view and access the properties of the object using the @Model.

//example 
return View(object) //in model class, return the object. @model Appname.Models.ClassName //use this binding object statement at the top of your Index Var data = @Model.data //accessing the model class object properties using the @Model

Q30. What is viewbag in mvc?

ViewBag is used to send data or objects from your controller to your view. It is a dynamic type property of the ControllerBase class.

//example 
ViewBag.data = “value"; In the model class, you can store some data to the ViewBag by attaching it to a property. Var data = ViewBag.data;

Note:- In the view, you can get the data from the ViewBag by using the property.

Q31. Explain the use of ViewModel in MVC?

The view model is used to represent the data on the view/page. It is a model for the view that is used for static text or data from/to the databases that can be represented in your view. A view model is just an object that has all the data and the properties to render a view. It can also be used for validation of data using IDataErrorInfo, handling user input, retrieving data from the database, combining data, etc. Also, display templates specified in the view model can be easily reused in other places.

Q32. What is use Bundle.Config.cs file in MVC4?

Bundle.config is a file created in default by MVC that is used to write the bundling code. When the individual request is sent to the server when the user references different files, there occurs unnecessary server overload. Bundling allows the developer to create a bundle of all the javascript and CSS files in the application. With this, all the files are fetched using a single request which improves the performance. Also, the bundles in the bundle.config files are minified. That is, all the extra space, the unnecessary comment is removed and scoped variable names are shortened to minimize the file size. Using the bundle and the minified files in the bundle.config files, it makes the job for a developer easy by referencing a set of files using a single request and thereby making the code clean and readable.

Q33. What is Partial View in MVC?

A partial view is a type of view that can be used as a child view in other views. It is a markup file with .cshtml extension, that renders HTML output. It can be used in the layout view and other views. By reusing the same view, it eliminates code reuse. It can also be used to break up large markup files into smaller components.

Q34. Enlist few different return types of a controller action method?

Different return types in the controller action method are,

View Result – this type returns results to the view page. It is a class that is derived from ViewResultBase class. return View();

Partial View Result – it returns partial view result to the partial view page. return PartialView();

Redirect Result – this type returns the result to a specific URL. return Redirect(“Home/Login”);

Redirect to Action Result – it returns the result to a specific controller and action. return RedirectToAction(“Login”, “Account”);

Json Result – this type returns Json data.

File Result – it returns a file in different formats.

Content Result – it returns different formats of the content to the view.

About Author :

  • Author of MVC interview questions

    Ketan Chauhan

    Ketan is a Software developer from Bengaluru, Karnataka, India.He works on latest Javascript technologoies like Angular, Node JS, React JS. He has also good knowledge of PHP and its frameworks like CodeIgniter, CakePHP,Laravel, Zend.He is always ready for learning new technologies. He loves playing Table tennis, watching and answersing developers queries.

Leave A Comment :

Valid name is required.

Valid name is required.

Valid email id is required.