Scaler
Practice
Resources
Contests
Online IDE
New
Free Mock
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders

Before you go!

Take this "ASP.NET MVC Interview Questions" interview guide with you

Welcome to Interviewbit, help us create the best experience for you!

Currently, You are a:

Few details about your education

College/University *
Enter the name of your college
Branch *
Year of completion *

Few details about your education

College/University *
Enter the name of your college
Branch *
Year of completion *

Few details about your career...

Current Company *
Enter company name
Experience *

You're all set!

Begin your success journey!

Sign Up using
Full name *
Email *
Password *

By creating an account, I acknowledge that I have read and agree to InterviewBit’s Terms and Privacy Policy .

Welcome back!

Log In using
Email *
Password *

ASP.NET MVC Interview Questions Last updated on Dec 16, 2021

Download PDF


Your requested download is ready!
Click here to download.

Introduction to ASP.NET MVC

ASP.NET MVC(ASP.NET stands for Active Server Pages in .NET framework and MVC stands for Model-View-Controller) is the framework that is more in demand for developing mobile and web applications. .NET MVC Framework provides a group of class libraries that helps you in developing highly scalable, high performance, and testable applications. MVC is a software design pattern that was introduced in 1970, specifies that the user should separate their code in such a way that the controller logic, data model, and user interface(view) are decoupled. This implies that it becomes simpler and easier to do maintenance and testing of an application.

Scope of ASP.NET MVC: Application developers in ASP.NET are high in demand now because companies look onto obtaining a competitive advantage using better custom software programming.

Enhance your chances of performing well in the interviews with the following list of interview questions on ASP.NET MVC.

Crack your next tech interview with confidence!
Take a free mock interview, get instant⚡️ feedback and recommendation💡

ASP.NET MVC Interview Questions for Freshers

1. What is ASP.NET MVC?

ASP.NET MVC is a lightweight framework for developing web and mobile applications. This framework divides an application into the three main components that make up MVC(Model, View, and Controller). In this MVC pattern for websites, action performance or data retrieval will be done when requests will be sent to a Controller that is in co-ordinance with the Model for doing such tasks. The model will retrieve the data and also store it in the database. The Controller selects the View for displaying and provides it along with the Model. The final page will be rendered by the View based on the data present in the Model.

MVC along with ASP.NET will give you a powerful and patterns-based way of developing dynamic websites as it enables a separation of concerns.

2. What are the three main components of an ASP.NET MVC application?

In the below-given figure, you can see three main components of the MVC architecture in ASP.NET and interaction among them.

The 3 main components of an ASP.NET MVC application are model, view, and controller.

  • Model: Model objects will implement the logic for the data domain of an application and has all the classes that handle data and business logic. Usually, model objects will retrieve and store the model state in the database.
  • Views: View is a component used for displaying the User Interface(UI) of an application. Generally, this UI will be created using the model data.
  • Controllers: The controller is a component used for handling the user interaction, model-related work, and selecting a view for rendering to display the UI. In an MVC application, for displaying the information the view will be responsible, for handling and responding to user input and interaction the controller will be responsible.

3. Explain about ASP.NET MVC 5.

The ASP.NET MVC 5 framework is the newest evolution of the ASP.NET web platform by Microsoft. A highly effective programming model will be provided by ASP.MVC 5, which promotes powerful extensibility, cleaner code architecture, test-driven development, in addition to all the ASP.NET benefits.

You can download a PDF version of Asp Net Mvc Interview Questions.

Download PDF


Your requested download is ready!
Click here to download.

4. What is Routing in ASP.NET MVC?

Routing in ASP.NET MVC is a pattern matching system that maps the incoming requests from the browser to specified actions of the MVC controller. When the application of ASP.NET MVC gets started, it registers one or multiple patterns with the framework route table so that it can inform the routing engine that what has to be done with the requests that are matching with those patterns. When a request is received by the routing engine during runtime, it matches that URL of the request against its registered URL patterns and provides the response based on a pattern match.

The URL pattern in routing will be considered based on the domain name part in the URL. For example, the URL pattern "{controller}/{action}/{id}" will look similar to localhost:1234/{controller}/{action}/{id}. Anything that comes after the"localhost:1234/" will be considered as the name of the controller. In the same manner, anything that comes after the controller name will be considered as the name of the action and then comes the id parameter value.

If the URL has nothing after the domain name, then the request will be handled by the default controller and action method. For example, the URL http://localhost:1234 will be handled by the Index() method and by the HomeController as per the default parameter configuration.

The below-given route table will show which Controllers, Action methods, and Id parameters will be handling the various URLs according to the above-provided default route.

The below figure shows request processing by routing engine and response sent by it. It provides a response based on URL match in the route table. When the URL of the request matches any of the route patterns that are registered in the route table then the request will be forwarded by the routing engine to the suitable handler for that request. Later the route will be processed and obtain a view on the UI. When the URL of the request doesn’t match with any of the route patterns that are registered, the routing engine will indicate that it can’t determine how to do request handling by returning an HTTP status code 404.

5. When to use Attribute Routing?

By using attribute routing, you can easily define some of the URI patterns that are most common in RESTful APIs. For example, resources will usually have child resources such as movies have actors, Clients will have orders, books have authors, etc. So it’s obvious to create URIs that reflect these kinds of relations such as /clients/1/orders. It is difficult to create these kinds of URIs using convention-based routing. With the help of attribute routing, it becomes easier for defining a route to this URI. 

You need to add an attribute to the controller action as given below:

[Route("clients/{cId}/orders")]
public IEnumerable<Order> ObtainOrdersByClient(int cId)
{
    //Statements
}

To enable attribute routing in ASP.NET MVC 5 application, you need to add a call to the method routes.MapMvcAttributeRoutes() within the RegisterRoutes() method of RouteConfig.cs file.

6. What is the Action Method in MVC?

The action methods in ASP.NET MVC will help for executing the request and generating a response to it. Every public method of the MVC Controller is considered an action method. If you want the public method to act as a non-action method, then it is possible to decorate the action method by using the attribute “NonAction”. This will restrict an action method from rendering on the browser.

A few points to be remembered while working with action methods are:

  • The action method is the public and non-static method
  • It cannot be the protected or private method
  • It cannot be an extension method
  • It can’t have ref and out parameters
  • It cannot be overloaded

It is possible to create action methods that will return an object of any type like an integer, a Boolean value, or a string. These return types will be wrapped in an ActionResult type that is appropriate before they are being rendered onto the response stream. Any return type that is not an action result will be converted into a string by the ASP.NET MVC and the string will be rendered into the browser. We can create a simple controller as per the code given below:

public class HomeController : Controller  
{  
   public ActionResult HelloInterviewbit()  
   {  
       ViewData["SayInterviewbit"] = "Interviewbit";  
       return View();  
   }  
   public string SayInterviewbit()  
   {  
       return "This is from 'SayInterviewbit'.";  
   }  
 
}

We must create a view for running SayInterviewbit() as it will return the View as views\home\SayInterviewbit.cshtml. For executing the second action method, it does not require the creation of a view. In the browser, the string will be rendered. It is possible for an void public method to act as an action method. This implies that any public method can become an action method.

7. What is Area in ASP.NET MVC?

The area will permit to divide the larger application into smaller units where every unit will have an MVC folder structure separately, exactly like the default MVC folder structure. 

Consider an example of a large enterprise application that might have different modules such as HR, finance, admin, marketing, etc. So for all these modules, an Area can have a separate MVC folder structure.

8. What is JsonResultType (JavaScript Object Notation Result Type) in ASP.NET MVC?

Action methods on controllers will return JsonResult that will be used within an AJAX application. From the “ActionResult” abstract class, this JsonResult class will be inherited. Here Json will be supplied with a single argument that must be serializable. The JSONResult object will serialize the specified object into JSON format.

Example:

public JsonResult JsonResultExample()
{
   return Json("Hello InterviewBit!!");
}

9. Explain about ASP.NET MVC filters.

The five types of Filters in ASP.NET MVC and order of their execution are as follows:

  • Authentication Filters: It executes before the execution of any other filter or action method. Authentication filter will make sure about whether you are a valid or invalid user. These filters will implement the interface IAuthenticationFilter.
  • Authorization Filters: It is responsible for checking User Access and is useful in implementing the authentication as well as authorization for controller actions. These authorization filters will implement the interface IAuthorizationFilterinterface. Examples of an Authorization filter are:
       - AuthorizeAttribute: It restricts access by optionally authorization and authentication.
       - RequireHttpsAttribute: It forces HTTP(HyperText Transfer Protocol) requests that are unsecured to be resent over HTTPS (HyperText Transfer Protocol Secure).
  • Action Filters: It is an attribute that can be applied to a controller action or a complete controller. It will be called before the execution of action begins and after the execution of action comes to end. These action filters will implement the interface IActionFilter in the framework, which has OnActionExecuting and OnActionExecuted methods. OnActionExecuting method executes before the Action and provides an opportunity for Action call cancelling. Since action filters are executed before and after a controller action executes, they can also be used for modifying the view data that is returned by a controller action.
  • Result Filters: It contains a logic that is to be executed before and after the execution of a view result. That means if you wish to modify a view result exactly before the rendering of view to the browser. These result filters are implemented from the IResultFilter interface in the framework, which has two methods namely OnResultExecuting and OnResultExecuted. An example of a result Filter is OutputCacheAttribute class which will provide output caching.
  • ExceptionFilters: It can be used for handling the errors that are raised by the controller actions or by the results of controller actions. The exception filters will implement the IExceptionFilter interface in the framework. It is very helpful during the execution pipeline where any unhandled exceptions might be thrown. An example for ExceptionFilter is HandleErrorAttribute class which will specify the way for handling an exception thrown by an action method.

It is possible to override the methods in your controller class if you wish to do so.

10. What are Action filters in ASP.NET MVC?

Action filters are the additional attributes in the ASP.NET MVC framework, that we can apply to either a section of the controller or to the entire controller for modifying the approach in which action will be executed. Action filter attributes are said to be special .NET classes as they are derived from the System.Attribute class and they can be attached to classes, properties, methods, and fields.

The following action filters are provided by ASP.NET MVC:

  • Output Cache: This action filter will cache the controller action output for a specified time.
  • Handle Error: This action filter will handle the errors raised during the execution of a controller action.
  • Authorize: This action filter will enable you for restricting to a particular role or user.

The below-given code will apply Output cache filter on an ActionFilterExampleController (Here, ActionFilterExampleController is just used as an example, You can apply action filters on any of the controllers). It specifies that the return value should be cached for 20 seconds.

public class ActionFilterExampleController: Controller
{
   [HttpGet]
   OutputCache(Duration = 20)]
   public string Index()
   {
       return DateTime.Now.ToString("T");
   }
}

11. What are the Advantages of ASP.NET MVC?

Following are a few advantages of ASP.NET MVC:

  • Separation of Concerns: The ASP.NET MVC framework will give you a clean separation of the User Interface(UI), Business Logic, Model/Data. That means it will give you a complete separation of Program logic from the UI.
  • Lightweight: The ASP.NET MVC framework will not make use of View State, it will result in bandwidth reduction of the requests to some extent.
  • Testability: The ASP.NET MVC framework will provide you with better Web application testability and will also give you very good support for test-driven development.
  • More Control: The ASP.NET MVC framework will support having control over JavaScript, CSS, and HTML in comparison with the traditional WebForms.
  • All features of ASP.NET: ASP.NET MVC framework is built on the top of ASP.NET framework, thus almost all the ASP.NET features such as roles, membership providers, etc., can be still used.

12. What is ViewBag and ViewData in ASP.NET MVC?

ViewBag:

  • It is a Wrapper developed around ViewData and is a dynamic property that uses dynamic features of C# 4.0.
  • ViewBag is mainly used for the passing of value from the Controller to View where it does not require to Type Caste the data during data retrieval.
  • This ViewBag is available only for the Current Request and will be destructed on re-direction.
  • Example:
    In the below given example, a string value will be set by the ViewBag object in Controller and later it will be displayed with the help of View.

Controller:

public class ExampleController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "This is about ViewBag ASP.NET MVC!!";
        return View();
    }
}

 View:

<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>IndexDisplay</title>
</head>
<body>
    <div>
        @ViewBag.Message
    </div>
</body>
</html>

ViewData:

  • It is derived from the class ViewDataDictionary and is originally a Dictionary object, which means it has Keys and Values where Keys represents the String and Values will be objects. Data will be stored in the form of Objects in ViewData.
  • ViewData is mainly used for the passing of value from the Controller to View. During retrieval of data, it needs to typecast the data into its original type since the data will be stored in the form of objects and it also needs NULL checks during data retrieval.
  • Similar to viewBag, this viewData is available only for Current Request and will be destructed upon redirection.
  • Example:
    In the below-given code, a string value will be set by the ViewData object in the Controller and later it will be displayed by the View.

Controller:

public class ExampleController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "This is about ViewData in ASP.NET MVC!!!";
        return View();
    }
}

  View:

<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <div>
        @ViewData["Message"]
    </div>
</body>
</html>

13. What are bundling and minification in ASP.NET MVC?

Bundling and minification are two techniques used for your web application in the ASP.NET MVC framework for improving the performance of the page load. Bundling will combine several files into a single file. Minification will perform different types of code optimizations to CSS and scripts, which will result in smaller payloads. With the help of bundling and minification, we can improve the performance of load time by reducing the requested assets(like JavaScript and CSS files) size and by reducing the number of requests to the server.

14. What is View Engine?

A View Engine is an MVC subsystem and has its own markup syntax. It will convert the template from the server-side into HTML markup and then render it to the browser. In the beginning, ASP.NET MVC was having a single view engine i.e., web forms(ASPX), from ASP.NET MVC 3 a Razor view engine Razor has been introduced. You can also make use of other view engines such as NHaml, Spark, etc., in ASP.NET MVC.

15. What is Razor View Engine in ASP.NET MVC?

Razor View Engine in ASP.NET MVC is a simple-syntax view engine used for creating a view of an application. It was released in January 2011 for Microsoft Visual Studio as a part of ASP.NET MVC 3.

Razor will make use of C# syntax for the purpose of embedding code in a page without the usage of ASP.NET delimiters: <%= %>. The file extension of Razor is “cshtml” for the C# programming language. It supports Test Driven Development(TDD) as it will not be dependent on the System.Web.UI.Page class.

16. Explain about TempData in ASP.NET MVC.

TempData is a dictionary object useful for the temporary storage of data. It is an instance of the Controller base class. It is useful in storing the data for the duration of an HTTP request, or we can say that it can store live data between two consecutive requests of HTTP. It is also useful in passing the state between action methods. TempData can be used only with the subsequent and current requests. It will make use of a session variable for storing the data. TempData needs typecasting during data retrieval.

Example: In the below-given code, employee details will be temporarily stored by TempData.

public ActionResult FirstRequest()
{
   List<string> TempDataDemo = new List<string>();
   TempDataDemo.Add("Harish");
   TempDataDemo.Add("Nagesh");
   TempDataDemo.Add("Rakshith");
   TempData["EmployeeName"] = TempDataDemo;
   return View();
}
public ActionResult ConsecutiveRequest()
{
   List<string> modelData = TempData["EmployeeName"] as List<string> ;
   TempData.Keep();
   return View(modelData);
}

17. Explain TDD(Test Driven Development) in ASP.NET MVC.

TDD or Test Driven Development is an approach where a test will be written before the completion of production code writing for the purpose of refactoring and fulfilling the test. TDD is also known as the Red-Green-Refactor method of development.

The Workflow of TDD is given below:

  • Requirement identification
  • Write a test case for automation
  • Tests will be executed and you need to make sure that the newer tests fail(red colour)
  • Write the complete production code
  • All tests have to be executed and passed.
  • Refactoring will be performed
  • The process should be repeated.

18. Explain state management in ASP.NET MVC.

The collection of input values(example: city, mobile number, e-mail id, etc.) of a specific web page is called as state of that page. By default, it is not possible to retain the values(states) provided on a single page of a web application, when you navigate to another web page. This nature of a web page is known as stateless behaviour.

You can make use of different state management techniques for retaining the values(state) across the web pages. The below-given common state management techniques will be supported by the ASP.NET MVC:

  • Session: It is a state management technique on the server-side that enables you for setting and read the user-specific values when the user navigates through different pages in a web application. These state variables will be stored by default in the host application’s main memory. It is also possible to configure this session variable to store on a SQL server database. The Session.Clear() method, can be used for removing the session variable from memory.
  • Query String: It is a state management technique on the client-side that is used for storing the values along with URL(Uniform Resource Locator). It cannot be used for storing the composite type values and also for storing confidential data such as passwords, as a query string area will be visible as part of the URL.
  • Cookies: It is a state management technique on the client-side that stores data in browsers memory. Based on settings, a few browsers may not be able to accept cookies.

19. How to implement Forms authentication in ASP.NET MVC?

Authentication means providing access to the user for a particular service through verification of his/her identity using his/her credentials such as email-id and password or username and password. It will make sure that the correct user will be authenticated or logged in for a particular service and the right service will be given to the specific user depending on their role.

Forms authentication in ASP.NET will be done after the completion of IIS(Internet Information Services) authentication. It is possible to configure forms authentication with the help of the forms element in the file web.config of your application. 

The forms authentication default attribute values are given below:

<system.web>
   <authenticationmode="Forms">
       <formsloginUrl="Login.aspx" protection="All" timeout="30" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="default.aspx" cookieless="UseDeviceProfile" enableCrossAppRedirects="false" />
   </authentication>
</system.web>

The FormsAuthentication class will automatically create the authentication cookie when it calls the methods RedirectFromLoginPage() or SetAuthCookie(). The value of an authentication cookie will be having the string representation for the signed and encrypted FormsAuthenticationTicket object.

20. What are the advantages of using Scaffolding in ASP.NET MVC?

Scaffolding is a code generation framework used for ASP.NET web applications that will be helpful in effectively generating the code for CRUD(Create, Read, Update, and Delete) operations against your database.

The Advantages of Scaffolding are as follows:

  • Minimal or no code for the creation of data-driven Web applications
  • Pages will be completely functional and will have various functionalities such as insert, edit, display, delete, paging, and sorting
  • Faster development time
  • Filters will be created for every boolean or foreign key field
  • The database schema based built-in data validation.

ASP.NET MVC Interview Questions for Experienced

21. Explain about ASP.NET MVC life cycle.

A Life cycle refers to a sequence of events or steps used for handling some kind of request or modifying the state of an application.

ASP.NET MVC has two life cycles. They are:

  • The Application Life Cycle: The ASP.NET application life cycle begins when a request is raised by a user. It refers to the time when the application process starts running IIS(Internet Information Services) till the time it ends. This is identified as the start and end events of an application in the startup file of your application. On Application Start, the application_start() method will be executed by the webserver. All global variables will be set to default values using this method. On the Application End, the application_end() method will be executed and this will be the final part of the application. The application will be unloaded from the memory in this part.
  • The Request Life Cycle: It refers to the series of events that will be executed each time when an HTTP request has been handled by the application. Routing is considered to be an entry point for each MVC application. After the request is received by the ASP.NET platform, it finds out how the request has to be handled with the help of the URL Routing Module. Modules are the components of a .NET that can be attached to the application life cycle. The routing module is helpful in matching the incoming URL(Uniform Resource Locator) to the routes that are defined in our application. All routes will be having a route handler associated with them and this route handler is considered to be an entry point to the MVC framework.

The route data will be converted by the MVC framework into a concrete controller that is capable of handling the requests. The major task after the creation of a controller is Action Execution. An action invoker component will find and select the suitable Action method for invoking the controller.

The next stage after the preparation of the action result is Result Execution. MVC will separate result declaration from result execution. If the result is of view, then it will find and render our view by calling the View Engine. If the result is not a view type, the action result will be executed on its own. This Result Execution will generate an original response to the actual HTTP request.

22. Explain RenderSection() in detail.

The RenderSection() method belongs to the WebPageBase class and is used for rendering the content of the defined section. The RenderSection() method’s first parameter will be the section name we wish to render at that particular location in the layout template. The second parameter will enable us for defining whether the rendering section is needed or not and this parameter is optional. If it is a “required” section, then an error will be thrown by the Razor if that section has not been implemented within a view template. It returns the HTML content for rendering purposes.

For example, a section named “note” in a layout page can be defined as follows:

@section note{
<h1>Header Content</h1>
}

The above-defined section can be rendered on the content page by using the below code: @RenderSection("note")

All sections are compulsory by default. To make the sections optional, you need to provide the value of the second parameter as a boolean value false.

<div id="body">
   @RenderSection("note", false)  //used for injecting the content in the defined section
   <section class="content-wrapper main-content clear-fix">
       @RenderBody()
   </section>
</div>

Using the above code, the section named “note” will be rendered on the content page. Here, the RenderBody method can be used for rendering the child page/view.

23. What are HTML Helper methods?

Helper methods are useful in rendering the HTML in the view. These methods will generate an HTML output as a part of the view. They need less coding as it can be reused across the views, so it is advantageous over HTML elements. The different built-in helper methods are available that can be used for generating the HTML for a few most commonly used HTML elements such as dropdown list, form, checkbox, etc. Along with this, it is also possible to create our own helper methods for custom HTML generation.

A few standard helper methods in MVC are given-below:

  • BeginForm: Used for rendering the HTML form tag
  • TextArea: Used for rendering the text area
  • TextBox: Used for rendering the text box
  • CheckBox: Used for rendering the check box
  • ListBox: Used for rendering the list box
  • DropDownList: Used for rendering the drop-down list
  • Password: Used for rendering the textBox for password input
  • Hidden: Used for rendering the hidden field
  • RadioButton: Used for rendering the radio button
  • ActionLink: Used for rendering the anchor.

24. What is the use of Validation Summary?

  • The Validation Summary helper method is useful in unordered list(UL element) generation that belongs to validation messages present in the object of Model State Dictionary.
  • It can be used for displaying all error messages related to all the fields. Also, it can be used for displaying custom error messages.
  • ValidationSummary will not only display the first message for any property instead it displays all error messages on the page. If you pass the first parameter value as true to ValidationSummary, only the messages having String.Empty as their name will be displayed.

For example, the below-given code will display a heading “Please fix the problem:” for a list of all the String.Empty messages. @Html.ValidationSummary(True, "Please fix the problem:")

25. What is a glimpse in ASP.NET MVC?

Glimpse is a web debugging and diagnostics tool that can be used with your ASP.NET or ASP.NET MVC applications for finding the information related to performance, debugging, and diagnostic. It helps you to obtain information regarding model binding, timelines, environment, routes, etc. It is possible to integrate Glimpse with insights into an application.

An intuitive user interface will be provided by Glimpse for examining the performance data of an application. Glimpse adds a widget to the web pages for viewing the performance-related data as you browse through the application web pages.

26. How to use multiple models to a single view in ASP.NET MVC?

ASP.NET MVC will permit only a single model to be bound to each view, but there are many workarounds for this. For example, the class ExpandoObject in the ASP.NET framework is a dynamic model which will be passed to a view.

Another common solution is the usage of ViewModel class(a class with several models), ViewBag(a property of the ControllerBase class which is dynamic), or ViewData(a dictionary object). It is also possible to use Tuple, JSON, and RenderAction.

In the example given below, you can get to know about how to use multiple models in a single view with the help of the ViewModel class. Here, ViewModel has two properties namely Managers and Employees that acts as a model.

ViewModel class:

public class ViewModel
{
   public IEnumerable<Manager> Managers { get; set; }
   public IEnumerable<Employee> Employees { get; set; }
}

Controller code:

public ActionResult IndexViewModel()
{
   ViewBag.Message = "Welcome to my example program!";
   ViewModel demomodel = new ViewModel();
   demomodel.Managers = GetManagers();
   demomodel.Employees = GetEmployees();
   return View(demomodel);
}

View code:

@using MultipleModelInOneView;
@model ViewModel
@{
   ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p><b>Manager List</b></p>
<table>
   <tr>
       <th>ManagerId</th>
       <th>Department</th>
       <th>Name</th>
   </tr>
   @foreach (Manager manager in Model.Managers)
   {
       <tr>
           <td>@manager.ManagerId</td>
           <td>@manager.Department</td>
           <td>@manager.Name</td>
       </tr>
   }
</table>
<p><b>Employee List</b></p>
<table>
   <tr>
       <th>EmployeeId</th>
       <th>Name</th>
       <th>Designation</th>
   </tr>
   @foreach (Employee employee in Model.Employees)
   {
       <tr>
           <td>@employee.EmployeeId</td>
           <td>@employee.Name</td>
           <td>@employee.Designation</td>
       </tr>
   }
</table>

27. Discuss a few necessary namespaces used in ASP.NET MVC.

Few significant namespaces that are used in ASP.NET MVC applications are:

  • System.Web.Mvc: It includes classes and interfaces that support the MVC pattern for Web applications in ASP.NET. It also has classes that represent controller factories, views, partial views, controllers, model binders, and action results.
  • System.Web.Mvc.Ajax: It consists of classes that support Ajax scripting within an application in ASP.NET MVC.
  • System.Web.Mvc.Html: It consists of classes that help to render HTML controls in an ASP.NET MVC application. Also, it has classes that will support partial views, validation, forms, links, and input controls.

28. What is the purpose of ”beforeRender()”, “beforeFilter()”, and “afterFilter()” functions in Controller?

  • beforeFilter(): This function will be executed before each action in the controller. It will inspect user permissions or check for an active session.
  • beforeRender(): This function will be executed before the rendering of the view and immediately after controller action logic. This function will not be frequently used, but it might be needed if you manually call the render() function before the end of a given action.
  • afterFilter(): This function will be called after each controller action, and also after the completion of rendering. It is the last method in the controller to run.

29. Explain different development approaches with the Entity framework.

Three different development approaches will be provided by the Entity framework while dealing with the database and data access layer in the application according to the need of the project. They are:

Database-First Approach: This approach will be used if there is an already existing database schema. Here, context and entities will be generated for the existing database using the EDM(Entity Data Model) wizard. This approach is considered to be the best for applications that will make use of an already existing database.

The Database-First approach is useful in the following cases:

  • While working with a legacy database.
  • While working on an application that is data-centric.
  • In scenarios such as the database design is carried out by another team and the development of the application begins only when the database is ready.

Code-First Approach: This approach is used when the existing database is not present for your application. In this approach, you will write the entities(domain classes) and context classes, then the database will be created from these classes with the help of migration commands.

This approach is considered to be the best for highly domain-centric applications and that will create the domain model classes in the beginning. Here, the database will be required only as a persistence mechanism for these newly created domain models. That implies, if a developer is following the principles of Domain-Driven Design(DDD), they will start the coding with the creation of domain classes and then the database required will be generated for persisting their data.

The Code First approach is useful in the following situations:

  • When there is an absence of logic in the database
  • When there is no context code and auto-generated model
  • If there is no manual modification of the database

Model-First Approach: In this approach, the entities, inheritance hierarchies, and relationships will be created directly on the visual designer and then can generate context class, database script, and entities using the visual model.

The Model-First approach is useful in the situation:

  • When we want to make use of the Visual Entity Designer.

30. What is a postback?

A postback will occur when clients make a request for a server response from their viewing page. Consider a simple example of a form completion by the user and hitting the “submit” button. In this case, the property IsPostBack will be true, so the request will be processed by the server and a response will be sent back to the client.

A postback helps to refresh the entire page when a data retrieval request has been made with a callback without completely refreshing the page.

ASP.NET MVC Scenario Based Interview Questions

31. Consider that you are developing an application that uses forms authentication in ASP.NET MVC.

A user named AdminLibrary is present in the user database. You will have the requirements as follows: - All users must be allowed to access the obtainBook() method. - Access to the modifyBook() method must be restricted for the AdminLibrary user. The controller must be implemented to meet the requirements. Which code segment will be used by you?

[Authorize]
public class LibraryControllerDemo:Controller
{
   [Allowanonymous] 
   public actionresult obtainBook()
   {
       return view();
   }
   [Authorize("AdminLibrary")]
   public actionresult modifyBook()
   {
       return view();
   }
}

[Allowanonymous] - It will allow all users to access the obtainBook() method.
[Authorize("AdminLibrary")]- It will restrict the AdminLibrary user from accessing the modifyBook() method.

32. Consider you want to restrict the users from requesting the method or Action directly in the URL of the browser. How it can be done?

Two of the methods to achieve the result for this scenario are:

Option 1:

The ChildActionMethod will permit you for restricting access to action methods that you don’t want users to directly request in the URL of the browser.

 [ChildActionOnly]
  public ActionResult demoPiper()
  {  
       return View();
  }

Now, the demoPiper() action method cannot be directly requested by the user through the URL of the browser.

Option 2:

In ASP.NET MVC, each controller’s method is accessed through a URL, and in case you don’t want an action created by you to be accessible through URL then you need to protect your action method with the help of the NonAction attribute provided by the MVC.

[NonAction]
public ActionResult demoPiper()
   {    
       return "demoPiper.com";
   }

After the demoPiper() method is declared as NonAction, if you try to access the method or action through URL, then HTTP 404 Not Found error will be returned.

33. Can we overload the action methods?

It is possible to overload the action methods by passing the name of the method in the ActionName attribute as given below:

[ActionName("ActionMethodExample")]
public ActionResult getInfo(int id)
{
   return "";
}

Another action method with the same name can be declared as given below:

public ActionResult getInfo()
{
   return "";
}

Now, these two getInfo() methods can be overloaded as they are having the same function name but differ in the number of arguments.

34. How do you manage unhandled exceptions in the Action method?

The HandleError attribute is used to manage the unhandled exceptions in the action method of the ASP.NET MVC application. Consider that the HandleError is not used in the application, and in case an unhandled exception is thrown by an action method then the default error page with sensitive information will be displayed to everybody.

It requires enabling custom errors in the web.config file, before the usage of HandleError.

<system.web>
   <customErrors mode="On" defaultRedirect="Error" />
</system.web>

Few properties of HandleError can be used for handling the exception. They are:

  • ExceptionType
  • Master
  • View
  • Order.

35. Explain how to create an ASP.NET MVC project with source code.

The following steps will explain how to create an ASP.NET MVC-based web application using Visual Studio 2019 IDE.

Creating a Web Project: Open the Visual Studio and click on the menu bar, then select the new option for creating a new project. You can see how to create a new project in the below-given image:

Select Project Type: Select the project type as an ASP.NET Web Application(.NET framework) and click on the Next button.

Provide Project Name: The name of the project should be provided in the following window and then click on Create button.

Select MVC Template: Now, select the MVC web template from the list of templates available, as we are implementing the MVC project. Then click on Create.

MVC Web Application Project Structure: The following image represents the project structure of the project created by us.

You can see that the Project structure is having three folders namely Model, View, and Controller. The default controller for the created application is the HomeController. By default, the HomeController consists of the following code:

// HomeController.vb
Public Class HomeController
   Inherits System.Web.Mvc.Controller
   Function Index() As ActionResult
       Return View()
   End Function
   Function About() As ActionResult
       ViewData("Message") = "Your application description page."
       Return View()
   End Function
   Function Contact() As ActionResult
       ViewData("Message") = "Your contact page."
       Return View()
   End Function
End Class

The Index file in the views folder will be the default file for the home controller.

// index.vbhtml
@Code
   ViewData("Title") = "Home Page"
End Code
<div class="jumbotron">
   <h1>ASP.NET</h1>
   <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
   <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="row">
   <div class="col-md-4">
       <h2>Getting started</h2>
       <p>
           ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
           enables a clean separation of concerns and gives you full control over markup
           for enjoyable, agile development.
       </p>
       <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p>
   </div>
   <div class="col-md-4">
       <h2>Get more libraries</h2>
       <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
       <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301866">Learn more »</a></p>
   </div>
   <div class="col-md-4">
       <h2>Web Hosting</h2>
       <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
       <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
   </div>
</div>

The above default code in the project will produce the below-given output when it is viewed in the browser:

Conclusion

The MVC pattern of ASP.NET has various advantages because of the separation between business logic, input logic, and user interface(UI) logic. But it has a few drawbacks such as it is completely controlled by JavaScript, HTML, and CSS, also it cannot be easily learned without any experiments.

To become industry competent, apart from learning the ASP.NET MVC, one must learn the commonly used C# programming language, SQL Server, OOPs, and some of the front-end technologies such as JavaScript, HTML, JQuery, etc.

Useful Interview Resources:

ASP.NET MVC MCQ

1.

Which filter executes first in ASP.NET MVC?

2.

What is ActionResult in ASP.NET MVC?

3.

In which format data will be returned from XML into the table?

4.

______ is the default authentication in Internet Information Services(IIS).

5.

Which Request Processing technique follows the ASP.NET?

6.

______ Namespace can be used for ASPX View Engine.

7.

Which among the below filters belong to filter types in the ASP.NET MVC application?

8.

Which is the default Viewstart Page in ASP.NET MVC?

9.

What is AuthConfig.cs in ASP.NET MVC?

10.

What is RouteConfig.cs in ASP.NET MVC?

11.

Which filter will be executed at the end in ASP.NET MVC?

12.

Scaffolding is a ______.

13.

Which among the below works on the client-side?

14.

What is meant by ViewResult()?

15.

DRY principle in ASP.NET represents ______.

Get Placed at Top Product Companies with Scaler Know More 
Get Placed at Top Product Companies with Scaler Know More 
Get Placed at Top Product Companies with Scaler
Sat transparent 640a34d454880bf68e3bfdf33f2389f2214043f59ad18b4c7f7b114e834fb257.svg

Point markers b3add1cc88e4996b2df6e0aedb9f0d1b65fa73c51b7ada8fbee3895a2aa11802.svg Personalised feedback report with solutions
Point markers b3add1cc88e4996b2df6e0aedb9f0d1b65fa73c51b7ada8fbee3895a2aa11802.svg Real life Interview Questions
Point markers b3add1cc88e4996b2df6e0aedb9f0d1b65fa73c51b7ada8fbee3895a2aa11802.svg Identify exact topics to improve

Your feedback is important to help us improve.
Free Mock Assessment
Help us know you better for the best experience
Current Employer *
Enter company name
College you graduated from *
Enter university name
Phone Number *
OTP will be sent to this number for verification
+91
+91
Change Number
Edit
Resend OTP
By Continuing I agree to be contacted by Scaler in the future.
Already have an account? Log in