24th
Dec
MVC interview questions

MVC interview questions

  • Sharad Jaiswal
  • 24th Dec, 2020
  • 757 Followers

MVC interview questions

1) What is MVC (Model view controller)?

Model–view–controller MVC is a software design pattern commonly used for developing user interfaces that divide the related program logic into three interconnected elements. This is done to separate internal representations of information from the ways information is presented to and accepted by the user.

2) Enlist few advantages of using MVC?

Below are few advantages of using MVC

  • Multiple view support: Due to the separation of the model from the view, the user interface can display multiple views of the same data at the same time.
  • Change Accommodation: User interfaces tend to change more frequently than business rules (different colors, fonts, screen layouts, and levels of support for new devices such as cell phones or PDAs)
  • SoC – Separation of Concerns: Separation of Concerns is one of the core advantages of ASP.NET MVC. The MVC framework provides a clean separation of the UI, Business Logic, Model or Data.
  •  More Control: The ASP.NET MVC framework provides more control over HTML, JavaScript, and CSS than the traditional WebForms.
  • Testability: ASP.NET MVC framework provides better testability of the Web Application and good support for test-driven development too.
  •   Lightweight: ASP.NET MVC framework doesn’t use View State and thus reduces the bandwidth of the requests to an extent.

3) Please explain complete MVC Request Life Cycle?

Request Life Cycle of Asp.net MVC consists of the sequence of events that happen every time an HTTP request is handled by our application.

Request Life Cycle of Asp.net MVC goes through

  • Routing
  • MvcHandler
  • Controller
  • Action Execution
  • View Result
  • View Engine
  • View

4) What do you mean by MVC Scaffolding?

Scaffolding is a technique used by many MVC frameworks like ASP.NET MVC, Ruby on Rails, Cake PHP and Node. JS etc., to generate code for basic CRUD (create, read, update, and delete) operations against your database effectively.

5) What is Razor in MVC?

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.

Download Free : MVC interview questions PDF

6) What is attribute based routing in MVC?

The MVC 5 now supports attribute based 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();
    }
}

7) What is TempData in MVC?

TempData in ASP.NET MVC is basically a dictionary object derived from TempDataDictionary. TempData stays for a subsequent HTTP Request as opposed to other options ( ViewBag and ViewData ) those stay only for the current request. So, TempdData can be used to maintain data between controller actions as well as redirects.

8) What is Partial View in MVC?

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.

9) What is the difference between ViewData and ViewBag?

Difference between ViewData and ViewBag

ViewData

  1. ViewData is used to pass data from a controller to view.
  2. It is derived from ViewDataDictionary class.
  3. It is available for the current request only.
  4. Requires typecasting for complex data type and checks for null values to avoid error.
  5. If redirection occurs, then its value becomes null.

ViewBag

  1. ViewBag is also used to pass data from the controller to the respective view.
  2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
  3. It is also available for the current request only.
  4. If redirection occurs, then its value becomes null.
  5. Doesn’t require typecasting for the complex data type.

10) What are Filters in MVC? List some?

Filters in ASP.NET MVC is a class that is executed before or after an action method is executed. It is a place where you can write custom logic that you want to execute. It can be executed either to an action method or a controller. You can apply a filter in two different ways, declarative and programmatic.

There are four types of built-in filters in ASP.NET MVC

  • Authorization filter
  • Action filter
  • Result filter
  • Exception filter.

OutputCache, HandleError, Authorize are few filters in MVC.

Take Free: Mvc MCQ & Quiz

11) 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 an action is executed. These filters allow pre and post-processing logic to be applied to an action method.

ASP.NET MVC framework includes several inbuilt action filters like OutputCache, HandleError, Authorize.

12) What is a Route in MVC?

Route in MVC is a URL pattern that is mapped to a handler. A handler can be a controller in the MVC application that processes the request. A route name may be used as a specific reference to a given route.

13) Explain what is routing in MVC?

Routing in ASP.NET is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions.ASP.NET MVC routes are responsible for determining which controller method to execute for a given URL.

A URL consists of the following properties:

  • Route Name
  • URL Pattern
  • Defaults
  • Constraints

14) What are the different types of filters available in MVC?

There are four different types of filters available in MVC. They are

  • Action Filters: Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter.
  • Authorization Filters: Authorization filters are used to implement authentication and authorization for controller actions.
  • Result Filters: Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.
  • Exception Filters: Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You can also use exception filters to log errors.

15) What is Default Route in MVC?

Default Route in MVC is route that is called whenever no url patterns are matched in MVC. It is configured in RouteConfig file that is available under App_Start directory.

Example

	routes.MapRoute(
		name: "Default",
		url: "{controller}/{action}/{id}",
		defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
	);

16) What are HTMLHelper in MVC?

HTMLHelper is a class in ASP.NET that contains various methods that assist to create 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.

17) What is need of display mode in MVC?

Display modes in ASP.NET MVC 5 provide a way of separating page content from the way it is rendered on various devices, like web, mobile, iPhone, iPod, and Windows Phones. All you need to do is to define a display mode for each device, or class of devices.

18) List the different return types of a controller action method?

The different return type of controller action methods are

  • ViewResult (View)
  • PartialviewResult (Partialview)
  • RedirectResult (Redirect)
  • Redirect To Action
  • Return content
  • Return JSON
  • Return JavaScript
  • Return File

19) What is RenderSection in MVC?

RenderSection() is a method of the WebPageBase class. It is a helper method that specifies the name of the section we want to render at that location in the layout template.

20) What is Output Caching in MVC?

Output Caching in MVC is used to dramatically improve the performance of a 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.

21) What is Bundling in MVC?

Bundling in MVC is used to load 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. Bundling classes are available under System.Web.Optimization namespace that is ScriptBundle, DynamicFolderBundle, StyleBundle.

22) How to render raw html in Asp.net MVC view?

You can use Html.Raw helper to render raw Html in Asp.net MVC

Syntax

@Html.Raw('<h1>Raw Example </h1>');

23) List different ways to manage session in MVC?

ASP.NET MVC provides three ways to manage session they are TempData, ViewData, and ViewBag.

24) What are Actions in ASP.Net MVC?

Action in ASP.NET MVC is responsible to execute requests and generate responses to it. By default, it generates a response in the form of ActionResult. Actions typically have a one-to-one mapping with user interactions.

25) Explain what is Dependency Resolution?

Dependency Resolver is a new concept that was introduced in MVC 3 which greatly simplified the use of. dependency injection in your applications. This made it easier to decouple application components, making them more configurable and easier to test.

26) List some important namespaces used in ASP.Net MVC?

Some important namespaces in ASP.NET MVC as given below:

  • System.Web.Mvc – This namespace contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller factories, action results, views, partial views, and model binders.
  • System.Web.Mvc.Ajax – This namespace contains classes that supports Ajax scripting in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings as well.
  • System.Web.Mvc.Html – This namespace contains classes that help render HTML controls in an MVC application. This namespace includes classes that support forms, input controls, links, partial views, and validation.

27) What are AJAX Helpers in MVC?

AJAX Helpers in MVC are used to create AJAX-enabled elements like as Ajax enabled forms and links which performs request asynchronously. AJAX Helpers are extension methods of the AJAXHelper class that exist in the System.Web.Mvc namespace.

28) What is Layout in MVC?

Layouts in MVC are used to provide a consistent look and feel on all the pages of our application. It is the same as defining the Master Pages but MVC provides some more functionalities.

29) List different types of Scaffoldings available in MVC?

In ASP.NET MVC there are six different types of Scaffold templates are available. They are

  • Empty: For creating an empty view and only model type is specified in the View page using @model.
  • Create: Creates a view with a form that helps to create a new record for the model. It automatically generates a label and input field for each property in the Model.
  • Delete: Creates a view with the list of records from the Model collection along with Delete link to delete records.
  • Details: Creates a view that displays a label and the value of each property of the Model.
  • Edit: Creates a view with a form for editing existing model data. It also generates a form with labels and fields for each property of the Model.
  • List: Creates a view with an HTML table that lists the model from the Model collection.

30) What is the use Glimpse in ASP.Net MVC?

Glimpse is a web debugging and diagnostics tool used to gain a better understanding of what's happening inside of your ASP.NET 4.0 application

It is open source NuGet packages that provide detailed performance, debugging and diagnostic information for ASP.NET apps. It's trivial to install, lightweight, ultra-fast, and displays key performance metrics at the bottom of every page.

31) What are Model Binders in ASP.Net MVC?

Model binder in ASP.NET MVC is used to map HTTP request data with a model. Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views) because POST and GET are automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene.

32) What is child actions in ASP.Net MVC?

A Child Action in ASP.NET MVC is kind of similar to that of a User Control in ASP.NET web forms. It allows for a controller to execute for a portion of the rendered area of a view, like in Web Forms where you can execute a UserControl for a portion of the rendered area of a page. [ChildActionOnly] attribute is used to indicate that an action method should be called only as a child action.

Example

[ChildActionOnly]
public ActionResult GetNews(string category)
{
    var newsProvider = new NewsProvider();
    var news = newsProvider.GetNews(category);
    return View(news);
}

33) What is Unobtrusive JavaScript?

Unobtrusive JavaScript is a best practice methodology for attaching JavaScript to the front-end of a website. It’s an ideal to strive toward and something we should bear in mind whenever we’re adding JavaScript to a site.

34) How to enable Attribute Routing in MVC?

Attribute Routing of ASP.net MVC enables us to define routing on top of the controller action method. It is a new type of routing that is supported by MVC5.

To enable Attribute Routing, we need to call the MapMvcAttributeRoutes method of the route collection class during configuration.

Example

public class RouteConfig
{
 public static void RegisterRoutes(RouteCollection routes)
 {
	routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
	//enabling attribute routing
	routes.MapMvcAttributeRoutes();
 }
}

35) What is use of Bundle.Config in MVC?

Bundling and minification techniques were introduced in MVC 4 to improve request load time. Bundling allows us to load the bunch of static files from the server into one HTTP request.

In asp.net MVC BundleConfig.cs the file is used to configure Bundling and minification.

36) Explain use of sections is MVC?

A section in MVC is used to specify a region of content within a layout. It expects one parameter which is the name of the section. A section can be defined as

@section header{

<h1>Header Content</h1>

}

Rendering a section in Asp.net MVC

@RenderSection("header")

By default, all sections are mandatory but you can make it optional by providing a false parameter eg. @RenderSection("header",false)

37) What are Non Action Selector in MVC?

NonAction selector attribute in MVC indicates that a public method of a Controller is not an action method. Use NonAction attribute when you want a public method in a controller but do not want to treat it as an action method.

Defining NonAction method

[NonAction]  
public void GetUserDetail(){  
     // some code inside here  
}  

38) What are asp.net MVC view engines?

In ASP.Net MVC, View engine is the one that works between your view and browser to provide valid HTML output to your browser by considering output provided by your view. There are view engines available for ASP.Net MVC some of them are Spark, NHaml, Razor, etc.

39) What is ViewBag in MVC?

ViewBag is a property or dictionary of objects that enable you to share values dynamically between the controller and view within ASP.NET MVC applications.ViewBag is accessible by a string as a key.

40) What is Asynchronous Controller in ASP.NET MVC?

An asynchronous controller in Asp.net MVC enables you to write asynchronous action methods. It allows you to perform a long-running operation(s) without making the running thread idle. Asynchronous action methods are useful when action must perform several independent long-running operations.

41) What is Cross Page Posting?

Cross page posting is the process of posting form data from another page. This is useful when you want to post data to another page and do not want to incur the overhead of reloading the current page.

42) What is Antiforgerytoken in ASP.NET MVC?

AntiForgeryToken feature of ASP.NET MVC which is used to generate a hidden form field (anti-forgery token) that is validated when the form is submitted. The anti-forgery token can be used to help protect your application against cross-site request forgery.

43) How to send result in JSON format in MVC?

You can use the JsonResult class to send results in JSON format in MVC. JsonResult is one of the types of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format).

44) What is MVVM pattern?

MVVM (Model–view–viewmodel) is a software architectural pattern that facilitates a separation of development of the graphical user interface from the development of the business logic or back-end logic. This pattern is used while dealing with views created primarily using WPF technology.

45) What is Route Constraints in ASP.NET MVC?

Route Constraint in ASP.NET MVC Routing allows us to apply a regular expression to a URL segment to restrict whether the route will match the request. In simple words, we say that Route constraint is a way to put some validation around the defined route.

46) What are different types of HTML Helpers available in ASP.NET MVC?

HtmlHelper class of MVC is used to generate html elements using the model class object in razor view. There are mainly three types of HTML helpers available in ASP.net MVC, they are

  • Inline Html Helpers
  • Built-In Html Helpers
  • Custom Html Helpers

47) Explain what are Url Helpers?

Url Helpers are primarily extension methods for you to easily create app-specific URLs in Asp.net MVC. ASP.NET MVC URL helpers are divided in two types HTML Links and Image Links.

48) What is use of Styles.Render()?

Styles.Render() method in MVC is used to include a specified CSS bundle at runtime.

In BundleConfig.cs file

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {            
        bundles.Add(new StyleBundle("~/bundles/css").Include(
                                                    "~/Content/bootstrap.css",
                                                    "~/Content/site.css"
                                                ));
        // add ScriptBundle here..  
        
    }
}

In your Razor View

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/bundles/css")
</head>
<body>
    @*html code removed for clarity *@
</body>
</html>

49) What is use of _ViewStart?

_ViewStart is a type of file that can be used to define common view code that you want to execute at the start of each View's rendering. It is similar to MasterPage in ASP.NET Web Form or as a layout template.

1 comment(s) :

  •   Reply
    img

    Mind Fuse

    23rd Dec, 2020
    "

    Good Questions on MVC. Please add the below questions in your List.

    • Please Explain Main Razor Syntax Rules?
    • What file extensions are used in razor views?
    • What is NonActionAttribute?
    • Explain the _viewstart in mvc?

Leave A Comment :

Valid name is required.

Valid name is required.

Valid email id is required.