ASP.NET MVC Interview Questions

Do you have any planned ASP.Net MVC interview in the coming days? This guide on ASP.NET MVC interview questions prepared by our team of experts will help you excel in your ASP.NET MVC interviews. These MVC interview questions will equip you to answer the questions on MVC design pattern, Routing in ASP.NET, Actions in MVC, Bootstrap in MVC, Action result in MVC, Attribute Routing in ASP.NET MVC, etc and land the best jobs as a .NET developer.

  • 4.6 Rating
  • 30 Question(s)
  • 25 Mins of Read
  • 8521 Reader(s)

Beginner

  • MVC stands for Model-View-Controller. It has been a software architectural pattern in computer science for many years.
  • It is a powerful means of separation of concern through which the maintenance and testing of the application becomes easy.
  • ASP.NET MVC is a framework built on top of the Microsoft .NET framework for building a web application that applies the general Model View Controller pattern to the ASP.NET framework.
  • Separation of concern: It is a software development concept that separates a computer program into different sections or concerns in which each concern has a different purpose.
  • By separating these sections, each can encapsulate information that can be developed and updated independently.
  • Model: These are the classes that represent the domain that the user works with. It describes the business logic and defines the business rules for manipulating the data.
  • View: It is responsible to display the data received from the controller. This is a template to dynamically generate HTML which transforms the Model into UI.
  • Controller: This is a special class that manages the relationship between the View and the Model. It responds to user input, talks to the Model, and decides which view to render.

There are following advantages of ASP.NET MVC over Web Forms (ASP.NET):

  • Separation of concern - To manage the complex application, MVC design pattern divides the ASP.NET MVC application into Model, View and Controller.
  • TDD - MVC framework provides more support to test-driven development.
  • Extensible and pluggable -By using the MVC framework we can design pluggable and extensible components which can be replaced or customized easier than Web Forms.
  • Full control over application behavior - MVC framework doesn’t support view state or server controls which provides more control over application behaviour and also reduce the bandwidth of the request.
  • ASP.NET features are supported - MVC framework is built on top of ASP.NET and therefore it supports ASP.NET features like provider's architecture, authentication and authorization scenarios, membership and roles, caching session.
  • URL routing mechanism - MVC framework provides URL routing feature which helps to build a more comprehensible and searchable URL for our application and this can help in search engine optimization.
  • Routing is a pattern matching mechanism of the incoming request to the URL pattern which is registered into route table and figure out what to do with the request.
  • Routing engine tries to match the incoming request with the routing table, if a match is found then it forwards the request to the appropriate controller and action otherwise it returns a 404 HTTP status code.
  • Layout page is similar to master pages in ASP.NET web forms which helps to maintain a consistent look and feel across multiple views within the application.
  • Compared to web forms layout offer simple syntax and greater flexibility.
  • Basic Structure of Layouts is as below:
<!DOCTYPE html>
<html>
  <head>
       <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width" />
         <title>@ViewBag.Title</title>
          @Styles.Render("~/Content/css")
          @Scripts.Render("~/bundles/modernizr")
 </head>
<body>
         @RenderBody()
         @Scripts.Render("~/bundles/jquery")
         @RenderSection("scripts", required: false)
</body>
</html>
  • A layout can be declared at the top of each child view as below
@{
         Layout = "~/Views/Shared/Layout.cshtml";
    }
  • The RenderBody method exists in the layout page to render child view. It is used for injecting content from child view into master view design.
  • It is like the ContentPlaceHolder in traditional WebForms.
  • Layout page can have only single RenderBody method.
  • Render page is used to call one page inside another page. For example, suppose we want to display some advertisement photos and also it will going to change frequently.
  • We create one common page of advertisement and insert this page where ever we would like to display it. When web page will render in the browser it will display advertisement content also.
  • When we change the advertisement content on one page, it will reflect on all the pages wherever this page is inserted
  • markup and render it to the browser.
  • The Razor view was introduced with ASP.NET MVC 3 and is the default view engine moving forward.
  • Razor provides an advanced syntax which supports HTML and server-side code using C# and VB.NET on the web page which minimizes the amount of code.
  • Razor syntax is easy to learn and much cleaner as compared to Web Form syntax.
  • Yes, we can remove default view engines provided by ASP.NET MVC.
 protected void Application_Start() 
{
         ViewEngines.Engines.Clear();
 }
  • faster and it is easily readable.
  • HTML Helper Class checks the controls at compile time and ensures that HTML controls get rendered correctly. HTML Helper has a set of methods which returns HTML strings.
  • For example

              The HTML helper @Html.TextBoxFor(m=>m.FirstName) will render the following html control
Output: <input id=" FirstName " name=" FirstName " type="text" value=" FirstName -Value" />

               This textbox is strongly bounded with Name properties of model m.

  • AJAX Helpers are used to create AJAX-enabled elements such as Ajax-enabled forms and links which perform the request asynchronously and these are extension methods of AJAXHelper class which exists in namespace — System.Web.MVC.
  • HTML helper class performs request synchronously.
  • Ajax helper class performs request asynchronously.
  • Partial view is similar to user control in asp.net web forms.
  • Partial views are used to re-usability purpose.
  • It’s been shared with multiple views, It is best practice to create a partial view in the shared folder
  • Partial views can be rendered in the following ways :

Html.Partial ()

Html.RenderPartial ()

  • For passing data from controller to view, ASP.NET MVC provides two options: ViewBag and ViewData.
  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  • Basically, it is a wrapper around the ViewData.
  • It doesn’t require typecasting for getting data.
  • ViewData is similar to ViewBag but is implemented using ViewDataDictionary class rather than a dynamic object.
  • The ViewDataDictionary class is like a regular key/value collection and is accessed through the ViewData property of the Controller class.
  • It’s required typecasting for getting data and check for null values to avoid an error.
  • The lifespan of ViewBag and ViewData is only during the current request.
  • If redirection occurs then viewdata and ViewBag values become null.
  • TempData is also a key, value pair same 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.
  • It’s used to store only one-time messages like error messages, validation messages.
  • All public methods of a controller class are treated as the action method.
  • If we do not want a public method to be an action method, we use the “NonActionAttribute” attribute.
[NonAction] 
public void ActionMethodName()
 { 
      // Method logic
 }
  • ViewModel is a class which contains fields and properties which is used to bind it to strongly type view.
  • ViewModel is used to pass data from controller to view.
  • ViewModel can have specific validation rules using data annotations.
  • Actions are the methods in Controller class which is responsible for returning the view or JSON data.
  • There are different Types of action results in ASP.NET MVC. Each result has a different type of result format to view page.
  • ViewResult - Returns a ViewResult which renders the specified or default to the response.
  • PartialViewResult- Returns a PartialViewResult which renders the specified or default partial view (means a view without its layout) to the response.
  • ContentResult - Returns a ContentResult, which writes the specific content (String) to the response.
  • JsonResult- Returns a JsonResult containing the output from serializing an object to JSON.
  • JavaScript- Returns a JavaScriptResult containing JavaScript code that is immediately executed when returned to the client.
  • FileResult- Returns a class that derives from FileResult, which writes binary content to the response.
  • Area is used to partition the big application into smaller units, each unit contains separate MVC folder structure same as default structure.Large application may have different modules and for all modules, if we have a common folder structure then it is very difficult to manage the application.
  • When we have created an area we require to register it in the "Application_Start" event in Global.asax. Below is the code snippet where area registration is done :
protected void Application_Start()
{
     AreaRegistration.RegisterAllAreas();
}
  • We generally spend more time to write the code for the CRUD operations like connect the database and write create, retrieve, update and delete code.
  • Microsoft has introduced the feature Scaffolding which generates the CRUD operation code for us.
  • Basically, it is a code generation framework which generates the basic controllers and views for the models using Microsoft T4 Templates.
  • Scaffolding blends with Entity Framework and creates an instance for the mapped entity model and generates code of all CRUD Operations

Advantages of Scaffolding

  • Rapid development on data-driven applications.
  • We can improve our views with minimal effort.
  • We can do the data validation based on the database schema.
  • Bootstrap is an open source front end web framework.
  • It is a collection of tools that contains HTML and CSS-based design templates along with JavaScript to create a responsive design for web applications.
  • Bootstrap provides all the elements and components which we require for buttons, menus, forms, labels, layout and all sorts of features.
  • When we create a new MVC project we will find Bootstrap.css and Bootstrap.JS in our project.
  • Once "TempData" is read in the current request its value is not available in the subsequent request.
  • If we want to preserve the value of the  "TempData" once we read it we need to call "Keep" method as shown in the code below
  • @TempData["value"];
  • TempData.Keep("value");
  • If you read “TempData” by using the “Peek” method it will persist for the next request.
string str = TempData.Peek("Td").ToString();

Advanced

  • When convention-based routing is complex to support certain URL patterns. This can be defined by using Attribute Routing.
  • For example when client ordering books based on author, or movies based on actors or items based on colours in such cases URL will look like “user/1/order”, “Item/1/color”
  • Such URL patterns are difficult to achieve using convention-based routing and it will take extra efforts.
  • It can be achieved by using attribute-based routing by adding an attribute to the controller action as shown below
[Route("Item/{itemId}/colourid")]
public IEnumerable<item> GetitemByColorid(int itemid, int colourid)
{
 //TO DO
}
  • There are four different ways for returning/rendering a view in ASP.NET MVC as given below
  • Return View() - This tells MVC to generate HTML to be displayed for the specified view and sends it to the browser.
  • Return RedirectToAction() - This tells MVC to redirect to specified action instead of rendering HTML. In this case, the browser receives the redirect notification and make a new request for the specified action.
  • Return Redirect() - This tells MVC to redirect to specified URL instead of rendering HTML. In this case, the browser receives the redirect notification and make a new request for the specified URL. In this case, you have to specify the full URL to redirect.
  • Return RedirectToRoute() - This tells MVC to look up the specifies route into the Route table that is defined in global.asax and then redirect to that controller/action defined in that route.
  • We can change the action method name by using “ActionName” attribute.
[ActionName("Write")] 
public ActionResult WriteSomething() 

    //TODO: return View();
 }
  • Here, “WriteSomething” action will be identified and called by the name “Write”.
  • Sometimes we want to perform logic either before an action method is called or after an action method runs.
  • This is achieved by decorating the controllers or actions with ASP.NET MVC attributes or custom attributes. An attribute or custom attribute implements the ASP.NET MVC filters and can contain a piece of code or logic which we want to execute before or after the action method call.
  • The ASP.NET MVC framework supports four different types of filters −

Authorization Filters − Implements the IAuthorizationFilter attribute.

Action Filters − Implements the IActionFilter attribute.

Result Filters − Implements the IResultFilter attribute.

Exception Filters − Implements the IExceptionFilter attribute.

  • All ASP.NET MVC filter are executed in order. Order of execution is given below:
  1. Authentication filters
  2. Authorization filters
  3. Action filters
  4. Result filters
  • Bundling is a technique to improve application performance by reducing the number of requests to the server by combining several individual script references into a single request.
  • Instead of fetching all resources one by one, we create a bundle (a logical group of files) and fetch that bundle in a single request.
  • In Asp.Net MVC we can create the bundle for CSS and JS files.
  • System.Web.Optimization namespace is used to create and configure the bundle.
  • Minification is a technique to remove unnecessary data from the JS and CSS file without changing its functionality.
  • It minifies the requests through a number of techniques, such as shortening variable names and removing whitespace and comments.
  • Change in the Web.Config file. 2. Change in the Global.asax.cs file.
  • Configuration change in web.config :
<appSettings>
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
  •  Code change in Global.asax.cs file
protected void Application_Start()
{
    HtmlHelper.ClientValidationEnabled = true;
    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}        
  • For enable/disable validation in a particular view.     

Set the below two properties in the View Razor code.

@{
    ViewBag.Title = "Index";
    HtmlHelper.ClientValidationEnabled = true;
    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;                                 
}
  • Below is the sequence of events that happen every time an HTTP request is handled by our application.
  • Routing: ASP.NET Routing is the first step in the MVC request cycle. When any new request comes that will be mapped with the registered URL patterns in the Route Table. If the matching pattern is available into route table, routing engine forwards this request to the corresponding IRouteHandler for that request. The default handler is the MvcHandler. The routing engine returns a 404 HTTP status code against that request if the pattern is not found in the Route Table.
  • When an application starts for the first time, it registers patterns to the Route Table. An application has only one Route Table and this is set up in the Global.asax file of the application.
  • MvcHandler: The role of  MvcHandler is to initiate the real processing of the MVC application. MVC handler implements the IHttpHandler interface and uses the ProcessRequest method for further processing.
  • Controller: The request object is sent to MvcHandler, which uses the IControllerFactory instance to create the controller class instance. The controller class object calls the Execute method.
  • Action Execution: Once the controller has been instantiated, a component called the action invoker finds and selects an appropriate Action method to invoke the controller.
  • View Result: The action method prepares response data based on the user inputs and executes and returns the result based on the return type.The result type can be ViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.
  • View Engine: If the result is a view type, the View Engine will be called and it's responsible for finding and rending view. It is handled by IViewEngine interface of the view engine. By default, ASP.NET MVC uses WebForm and Razor view engines. If the result is not a view, the action result will execute on its own.
  • View: There are different action results like text string, a binary file or a JSON formatted data, ViewResult, which renders and returns an HTML page to the browser by using the view engine.

Yes, we can map multiple URLs. To achieve this we require to make two entries with different key names and specify the same controller and action name.

  • To restrict the type of HTTP calls to GET or POST only we require to decorate the MVC action by “HttpGet” or “HttpPost” attribute.
  • As shown in below code example “CustomerList” action method can only be invoked by “HttpGet”. If we try to make Http post on “CustomerList” it will throw an error.
[HttpGet]
public ViewResult CustomerList()
{
List<Customer> list = GetCustomerList();
retrun view("CustomerList",list)
}

Description

ASP.NET Core MVC is a rich web application framework for building web apps and APIs using the Model-View-Controller design pattern. This is the 6th most popular framework in India and 10th most popular in top 1 Million sites in framework around the world.
 

Today, ASP.NET MVC framework has occupied the web market replacing many competing frameworks with it. This has increased the demand for skilled MVC developers to create appealing, fast, and secure web applications. According to Neuvoo, the average ASP.NET MVC Developer salary in the USA is $110,000 per year or $56.41 per hour. Entry-level positions start at $70,000 per year while most experienced workers make up to $187,000 per year.
 

Many companies like Innovecture LLC., eXcell, IntelliX Software, Inc., CyberCoders, Workbridge Associates, GemFind, etc. hire ASP.NET MVC skilled professionals. With this skill, an individual can play various roles like C# ASP.NET Developer, ASP.NET MVC Developer, ASP.NET/SQL Server Developer, Full-Stack Developer (GitHub, ASP.NET MVC), etc. in the organizations.   
 

If you are applying for the ASP.NET MVC developer/programmer job, then it is good to prepare beforehand with these expert designed guide of .net MVC interview questions and answers for both experienced as well as freshers. These ASP.NET MVC interview questions and answers will definitely help you to crack your ASP.NET MVC interview successfully.
 

After going through these ASP.NET MVC interview questions and answers with top interview tips, you will be able to confidently face an interview and will boost your core interview skills that help you perform better. Prepare well and in time!
 

All the best!

Read More
Levels