ASP.NET MVC Interview Questions and Answers

ASP.NET MVC Interview Questions and Answers

In this article, I am going to discuss the most frequently asked ASP.NET MVC Interview Questions with answers. I am sure at the end of this article, you will be in a better position to answer most of the ASP.NET MVC Interview Questions. As part of this article, we are going to discuss the following ASP.NET MVC Interview Questions and Answers.

  1. Explain MVC (Model-View-Controller) in general?
  2. What is ASP.NET MVC?
  3. What are Model, View, and Controller from ASP.NET MVC Point of view?
  4. Explain the advantages of ASP.NET MVC?
  5. What is the difference between 3-layer architecture and MVC architecture?
  6. What are the differences between ASP.NET MVC and ASP.NET WebForms?
  7. Can you please explain the request flow in the ASP.NET MVC framework?
  8. What are the important namespaces used in ASP.NET MVC?
  9. What is View Model in ASP.NET MVC?
  10. What are Action methods in ASP.NET MVC?
  11. What is ActionResult and how is it different from others?
  12. How to make a Non-Action method in ASP.NET MVC?
  13. How you can change the action method name in ASP.NET MVC?
  14. How to restrict an action method to be invoked only by HTTP GET, POST, PUT or DELETE?
  15. How to determine an action method is invoked by HTTP GET or POST?
  16. How to determine an AJAX request?
  17. What is Child action and how to invoke it?
  18. What are Partial Views in ASP.NET MVC and it’s needed?
  19. What are the Layouts in ASP.NET MVC
  20. What are Sections in ASP.NET MVC?
  21. What are RenderBody and RenderPage in ASP.NET MVC?
  22. What are the Styles.Render and Scripts.Render?
  23. How to enable and disable optimizations in ASP.NET MVC?
  24. What is _ViewStart?
  25. What are the different ways of rendering layout in ASP.NET MVC?
  26. What is the App_Start folder in ASP.NET MVC?
  27. What are the different ways of returning/rendering a view in ASP.NET MVC?
  28. What is Area in ASP.NET MVC?
  29. How to register Area in ASP.NET MVC?
  30. What is Scaffolding?
  31. What are the differences between ViewData, ViewBag, TempData, and Session?
  32. How to control Session behavior in ASP.NET MVC?
  33. How is TempData related to Session in ASP.NET MVC?
Explain MVC (Model-View-Controller) in general?

This is one of the most frequently asked ASP.NET MVC Interview Questions. So here we will discuss what is MVC design pattern is and what are the role and responsibilities of Model, View, and Controller in details.

MVC is an architectural software design pattern that is used for developing interactive applications where there would be user interaction involved and based on the user interaction some event handling occurs. So, this Model View Controller (MVC) design pattern is not only used for developing web-based applications but it can also be used for Desktop or mobile-based applications where there are user interactions involved and based on the user interaction some event handling occurs.

This MVC (Model-View-Controller) design pattern was introduced in the 1970s which basically divides an application into 3 major components such as Model, View, and Controller. The main objective of the MVC design pattern is the separation of concerns. It means the domain model and business logic are separated from the user interface (i.e. view). Thus, maintenance and testing of the application become simpler and easier.

ASP.NET MVC Interview Questions and Answers

The Model in MVC Design Pattern

The Model is the component in MVC design pattern which manages that data i.e. state of the application in memory. It represents a set of classes that describe the application’s business logic, validation logic, and data access logic. For example, an Employee object (Model) might retrieve the data from a database, operate on it, validate the data and then write the updated information back to an Employee table in the database. So the model is basically used to contain business (domain) data and business logic.

The View in MVC Design Pattern

The view is the component in the MVC design pattern which represents the user interface with which the end-user can interact. Basically, the view is used to render the domain data (i.e. business data). It creates the user interface with data from the model with which the end-user can interact. An example would be an edit view of a product table that displays text boxes, dropdown lists, and checkboxes based on the current state of a Product object.

The Controller in MVC Design Pattern

The Controller is the component in the MVC design pattern which contains the control flow logic. It is the one that will interact with both the models and views to control the flow of application execution. So, the controller component responds to user actions. Based on the user actions, the respective controller work with the model and view and sends responds back to the user.

What is ASP.NET MVC?

In many ASP.NET MVC interviews, they asked this question to check whether you know the difference between MVC and ASP.NET MVC. The first thing is first. So, remember both ASP.NET MVC and MVC are two different things altogether. 

The ASP.NET MVC is an open-source web application development framework from Microsoft that is based on MVC (Model-View-Controller) architectural design pattern which provides a clean separation of code. This is the most customizable and extensible platform or framework provided by Microsoft.

So, the point that you need to remember is, ASP.NET MVC is a Framework whereas MVC is a Design Pattern and the ASP.NET MVC Framework is based on MVC Design Pattern.

What are Model, View, and Controller from ASP.NET MVC Point of view?

We already discussed What are Model, View, and Controllers from MVC Design pattern Point of View. So, let discuss What are Model, View, and Controllers from ASP.NET MVC Point of view.

Model in ASP.NET MVC:
  1. In MVC, the models are basically C#.NET or VB.NET classes.
  2. The Models are basically used to manage the business data and business logic.
  3. This is the component that can be accessed by both the controller and view.
  4. The model component can be used by a controller to pass the data to a view.
  5. It can also be used by a view, in order to display the data the in page (HTML output)
View in ASP.NET MVC:
  1. In the ASP.NET MVC application, the views are nothing but the cshtml or vbhtml pages without having a code-behind file.
  2. All page specific HTML generation and formatting can be done inside view.
  3. A request to view can only be made from a controller’s action method.
  4. The view is only responsible for displaying the data.
  5.  By default, views are stored in the Views folder of an ASP.NET MVC application.
Controller in ASP.NET MVC:
  1. In ASP.NET MVC, the controller is basically a C# or VB.NET class that inherits from System.Web.Mvc.Controller.
  2. This is the component that has access to both the Models and Views in order to control the flow of the application execution.
  3. The Controller class contains action methods that are going to respond to the incoming URL.
  4. A controller can access and use the model classes to pass the data to a view.
  5. By default, controllers have stored in the Controllers folder an ASP.NET MVC application.
What are the Advantages of ASP.NET MVC?

This is one of the ASP.NET MVC questions asked in the interview to check whether you know why you are using MVC or not. So let us discuss what are the advantages of using ASP.NET MVC or you can say why we need to use ASP.NET MVC to develop a web application.

  1. The ASP.NET MVC Views are lightweight as compared to ASP.NET Web Forms because it does not use view state or any server-based forms or controls to render the data.
  2. As we are separating the view from the rest of the application which enables us to change of view (technology) in the future without affecting the rest of the application. For example, we might have views in Silverlight or HTML5.
  3. Each developer based on his expertise or experience can work on different parts of the application without stepping on each other toes. For example, one developer can work on the view while the second developer can work on the controller logic and the third developer can focus on the business logic in the model by interacting with the database.
  4. With the introduction of Attribute Routing, now it is very easy to create Restful or User-friendly URL’s which enable SEO to rank your page high.
  5. The ASP.NET MVC provides better support for test-driven development (TDD). This is because we can focus on one aspect at a time i.e. we can focus on the view without worrying about business logic as each component can be developed independently and also can be mocked easily.
  6. As the MVC design pattern divides the application into three major components such as Model, View, and Controller which make it easier to manage the application complexity.
  7. MVC framework components were designed to be pluggable and extensible and therefore can be replaced or customized in the future very easily
  8. AS the MVC framework is built on top of ASP.NET, so, we can use most of the ASP.NET features such as the authentication and authorization scenarios, membership and roles, caching, session and many more.
What is the difference between 3-layer architecture and MVC architecture?

This is one of the frequently asked ASP.NET MVC Interview Questions. So, let us understand the differences between them.

The 3-layer architecture separates the application into 3 components which consist of Presentation Layer, Business Layer, and Data Access Layer. In 3-layer architecture, the user is going to interacts with the Presentation layer only. 3-layer is a linear architecture.

The MVC architecture separates the application into three major components such as Model, View, and Controller. In MVC architecture, the user is going to interacts with the controller with the help of view. MVC is a triangle architecture.

MVC does not replace 3-layer architecture. Typically MVC and 3-layer architecture are used together and the MVC Design Pattern acts as the Presentation layer of the application.

What are the differences between ASP.NET MVC and ASP.NET WebForms?

This is one of the Frequently asked ASP.NET MVC interview questions and answers.

The ASP.NET Web Forms uses the Page controller pattern approach for rendering the layout whereas ASP.NET MVC uses the Front controller approach for rendering the layout. In the case of the Page controller Pattern approach, every aspx page having its own controller i.e. the code-behind file which is used to process the incoming request. Whereas, in ASP.NET MVC, a common controller can process the requests for all pages.

If you are visiting ASP.NET forums and communities, we will find the following questions frequently i.e.

  1. What is the difference between ASP.NET MVC and ASP.NET WebForms?
  2. Is ASP.NET MVC going to replace ASP.NET WebForms?

The first and the important thing that you need to remember is, the ASP.NET MVC Framework is not going to replace the ASP.NET WebForms Framework. Both technologies exist and both can be used to develop ASP.NET applications. Here we are going to discuss, what are the advantages and disadvantages of both these technologies one over another.

  1. In ASP.NET WebForms there is no separation of concerns as every page (.aspx) has its own controller (i.e. code-behind i.e. aspx.cs/.vb file). As a result, both are tightly coupled. Whereas the main objective of ASP.NET MVC is the clean separation of concerns as View and Controller are cleanly separate and also they are not tightly coupled.
  2. Because of the tightly coupled behavior in ASP.NET Web Forms (i.e. .aspx page and its code-behind file), unit testing is really a nightmare for a developer. Whereas in ASP.NET MVC unit testing is achieved very easily as they are not tightly coupled.
  3. ASP.NET Web Forms follows a Page Life cycle. Whereas in ASP.NET MVC there is no such Page Life cycle like WebForms. The request cycle is simple in the ASP.NET MVC model.
  4. ASP.NET MVC views are lightweight, as they do not use ViewState whereas ASP.NET Web Forms pages are not lightweight as they use ViewState.
  5. Complex applications can be easily managed in ASP.NET MVC because of the separation of concerns. Different components of the application can be divided into Model, View, and Controller.
  6. ASP.NET web form has file-based URLs means the file name exists in the URLs must have its physical existence whereas ASP.NET MVC has route-based URLs means URLs are divided into controllers and actions and moreover it is based on controller not on physical file.
  7. ASP.NET web form has Master Pages for consistent looks and feels whereas ASP.NET MVC has Layouts for consistent looks and feels.
  8. ASP.NET web form has User Controls for code re-usability whereas ASP.NET MVC has Partial Views for code re-usability.
  9. ASP.NET Web Form is not Open Source whereas ASP.NET Web MVC is an Open Source.
  10. ASP.NET Web Form has server controls whereas ASP.NET MVC has HTML helpers.
Can you please explain the request flow in the ASP.NET MVC framework?

This is one of the Frequently asked ASP.NET MVC interview questions and answers. If you are going for an ASP.NET MVC interview, then you definitely face this question i.e. Explain the Request Flow of ASP.NET MVC Application. So here you need to explain how a request is handled in the ASP.NET MVC framework. This is one of the frequently asked ASP.NET MVC Interview questions.

The Request flow for ASP.NET MVC framework is as follows:

In ASP.NET MVC application when the client makes a request for a resource from the browser then that request is handled by the Routing engine and then the routing engine navigates that request to the appropriate Controller. Then the controller plays its role and executes the action method based on the user action and if needed then it works with the model object in order to serve the request. Once it works with the model, then it passes that model to a view and that view transforms that model and generates an appropriate response that is rendered to the client.

The point that you need to be noted that, the difference between WebForms and MVC is that in MVC we don’t have the Page concept whereas, in Legacy like ASP.NET Web Forms application, we do have pages like .aspx. So if your question is, Then how do the requests are been pointed in MVC? The answer is via Controller. This special class is responsible for generating the response and sending the data back to the client.

For instance, the URL http://www.xyz.net/Book/Create Says that it is requesting for the Controller class name “Book” and the Action Method name called “Create”.

What are the important namespaces used in ASP.NET MVC?

This question is not that important, but you should what are the important namespaces you used in the ASP.NET MVC application. The following are some of the important namespaces:

  1. 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.
  2. System.Web.Mvc.Ajax – This namespace contains classes that support Ajax scripting in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings as well.
  3. 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.
What is ViewModel in ASP.NET MVC?

In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in the strongly-typed view. It is used to pass data from controller to strongly-typed view.

Key Points about ViewModel
  1. ViewModel contains fields that are represented in the view (for LabelFor, EditorFor, DisplayFor helpers).
  2. ViewModel can have specific validation rules using data annotations.
  3. ViewModel can have multiple entities or objects from different data models or data source.
What are Action methods in ASP.NET MVC?

All public methods of a Controller in ASP.NET MVC application which respond to the incoming URL are considered as Action Methods.

Controller actions are methods defined in the controller class and responsible to perform required operations on the user’s inputs like form values, query strings values, etc. with the help of Model and passing the results back to the View. Asp.net MVC has the following built-in ActionResults Type and Helper methods:

  1. ViewResult – Returns a ViewResult which renders the specified or default view by using the controller View() helper method.
  2. PartialViewResult – Returns a PartialViewResult which renders the specified or default partial view (means a view without its layout) by using the controller PartialView() helper method.
  3. RedirectResult – Returns a RedirectResult which Issues an HTTP 301 or 302 redirection to a specific URL by using controller Redirect() helper method.
  4. RedirectToRouteResult – Returns a RedirectToRouteResult which Issues an HTTP 301 or 302 redirection to an action method or specific route entry by using controller RedirectToAction(), RedirectToActionPermanent(), RedirectToRoute(), RedirectToRoutePermanent() helper methods.
  5. ContentResult – Returns a ContentResult which renders raw text like “Hello, DotNet Tutorials!” by using the controller Content() helper method.
  6. JsonResult – Returns a JsonResult which serializes an object in JSON format ( like as “{ “Message”: Hello, World! }”) and renders it by using controller Json() helper method.
  7. JavaScriptResult – Returns a JavaScriptResult which renders a snippet of JavaScript code like as “function hello() { alert(Hello, World!); }” by using controller JavaScript() helper method. This is used only in AJAX scenarios.
  8. FileResult – Returns a FileResult which renders the contents of a file like PDF, DOC, Excel, etc. by using the controller File() helper method.
  9. EmptyResult – Returns no result returned by an action. This has no controller helper method.
  10. HttpNotFoundResult – Returns an HttpNotFoundResult which renders a 404 HTTP Status Code response by using controller HttpNotFound() helper method.
  11. HttpUnauthorizedResult – Returns an HttpUnauthorizedResult which renders a 401 HTTP Status Code (means “not authorized”) response. This has no controller helper method. This is used for authentication (forms authentication or Windows authentication) to ask the user to log in.
  12. HttpStatusCodeResult – Returns an HttpStatusCodeResult which renders a specified HTTP code response. This has no controller helper method.

Note: All public methods of a Controller in an ASP.NET MVC application are considered as Action Methods by default. If we want our controller to have a Non-Action Method, we need to explicitly mark it with NonAction attribute as follows:

What is ActionResult and how is it different from others?

The ActionResult class is the base class for all action results. An action result can be of type ViewResult, JsonResult, RedirectResult and so on. Hence, when your action method returns multiple results based on different conditions, ActionResult is the best choice. Since it can return any type of result.

ASP.NET MVC Action Methods Interview Questions and Answers

How to make a Non-Action method in ASP.NET MVC?

By default, the ASP.NET MVC framework treats all public methods of a controller class as action methods. If you do not want a public method to be an action method, you must mark that method with the NonActionAttribute attribute.

[NonAction]
public void DoSomething()
{
    // Method logic
}
Can you change the action method name?

We can also change the action method name by using the ActionName attribute. Now action method will be called by the name defined by the ActionName attribute.

[ActionName("DoAction")]
public ActionResult DoSomething()
{
    //TODO: return View();
}

Now, DoSomething action will be identified and called by the name DoAction.

How to restrict an action method to be invoked only by HTTP GET, POST, PUT or DELETE?

By default, each and every action method can be invoked by an HTTP request (i.e. GET, PUT, POST, and DELETE). But you can restrict an action to be invoked only by a specific HTTP request by applying HttpGet or HttpPost or HttpPut or HttpDelete attribute.

If you want to restrict an action method for HTTP Get request only then decorate it with HttpGet action method selector attribute as given below:

[HttpGet]
public ActionResult Index()
{
    //TODO: 
     return View();
}
How to determine an action method is invoked by HTTP GET or POST?

By using the HttpMethod property of HttpRequestBase class, you can find out whether an action is invoked by HTTP GET or POST.

public ActionResult Index(int? id)
{
    if (Request.HttpMethod == "GET")
    {
        //TODO:
    }
    else if (Request.HttpMethod == "POST")
    {
        //TODO:
    }
    else
    {
        //TODO:
    }
    return View();
}
How to determine an AJAX request?

We can determine an AJAX request by using Request.IsAjaxRequest() method. It will return true if the request is an AJAX request else returns false.

public ActionResult DoSomething()
{
    if (Request.IsAjaxRequest())
    {
        //TODO:
    }
    return View();
}
What is Child action and how to invoke it?

Child actions are useful for creating reusable widgets that could be embedded in your views. In ASP.NET MVC partial views are used to create reusable widgets and a partial can be rendered by an action method. This action method can have a child attribute and has its independent MVC lifecycle from the parent view. Also, an action that has a child’s attribute cannot be called independently. It always will be called within a parent view otherwise it would give an error.

[ChildActionOnly]
public ActionResult MenuBar()
{
    //TODO:
    return PartialView();
}

A child action is invoked by using @Html.RenderAction or @Html.Action helper methods from inside of a view.

What are Partial Views in ASP.NET MVC and it’s needed?

This is one of the Frequently asked ASP.NET MVC interview questions and answers. A partial view is like as user control in ASP.NET Webforms that are used for code re-usability. Partial views help us to reduce code duplication. Hence partial views are reusable views like Header and Footer views. We can use the partial view to display blog comments, product category, social bookmarks buttons, a dynamic ticker, calendar, etc.

It is best practice to create a partial view in the shared folder and partial view name is preceded by “_”, but it is not mandatory. The “_” before view name specifies that it is a reusable component i.e. partial view.

What are the Layouts in ASP.NET MVC?

Layouts are used to maintain a consistent look and feel across multiple views within the ASP.NET MVC application. As compared to Web Forms, layouts serve the same purpose as master pages but offer a simple syntax and greater flexibility. A basic structure of layout is given 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>

You can use a layout to define a common template for your site. A layout can be declared at the top of view as:

@{
    Layout = "~/Views/Shared/SiteLayout.cshtml";
}
What are Sections in ASP.NET MVC?

A section allows us to specify a region of content within a layout. It expects one parameter which is the name of the section. If you don’t provide that, an exception will be thrown. A section on a layout page can be defined by using the following code.
@section header{ <h1>Header Content</h1> }

You can render the above-defined section header on the content page as given below:
@RenderSection(“header”)

By default, sections are mandatory. To make sections optional just provides the second parameter value as false, which is a Boolean value.
@RenderSection(“header”,false)

Note: A view can define only those sections that are referred to in the layout page otherwise an exception will be thrown.

What are RenderBody and RenderPage in ASP.NET MVC?

This is one of the Frequently asked ASP.NET MVC interview questions and answers. RenderBody method exists in the Layout page to render child page/view. It is just like the ContentPlaceHolder on the master page. A layout page can have only one RenderBody method.

<body>
    @RenderBody()
    @RenderPage("~/Views/Shared/_Header.cshtml")
    @RenderPage("~/Views/Shared/_Footer.cshtml")
    @RenderSection("scripts", false)

    @section scripts{
        <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    }
</body>

The reader page method also exists in the Layout page to render another page that exists in your application. A layout page can have multiple RenderPage methods.

@RenderPage(“~/Views/Shared/_Header.cshtml”)

What are the Styles.Render and Scripts.Render?

Style.Render is used to render a bundle of CSS files defined within BundleConfig.cs files. Styles.Render create style tag(s) for the CSS bundle. Like Style.Render, Scripts.Render is also used to render a bundle of Script files by rendering script tag(s) for the Script bundle.

public class BundleConfig
{
    // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

        // Use the development version of Modernizr to develop with and learn from. Then, when you're
        // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));

        bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.js",
                  "~/Scripts/respond.js"));

        bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/site.css"));
    }
}

The Styles.Render and Scripts.Render generate multiple styles and script tags for each item in the CSS bundle and Script bundle when optimizations are disabled. When optimizations are enabled, Styles.Render and Scripts.Render generate a single style and script tag to a version-stamped URL which represents the entire bundle for CSS and Scripts.

How to enable and disable optimizations in ASP.NET MVC?

We can enable and disable optimizations by setting EnableOptimizations property of BundleTable class to true or false within Global.asax.cs file as shown below.

Views Interview Questions in ASP.NET MVC

What is _ViewStart?

The _ViewStart.cshml page is used to serve a common layout page(s) for a group of views. The code within this file is executed before the code in any view placed in the same directory. This file is also recursively applied to any view within a subdirectory.

What are the different ways of rendering layout in ASP.NET MVC?

There are following four different ways of rendering layout in ASP.NET MVC:

Using _ViewStart file in the root directory of the Views folder:

The _ViewStart file within Views folder is used to server the default Layout page for your ASP.NET MVC application. You can also change the default rendering of layouts within _ViewStart file based on the controller as shown below:

@{
    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToSt ring();
    string layout = "";
    if (controller == "Admin")
    {
        layout = "~/Views/Shared/_AdminLayout.cshtml";
    }
    else
    {
        layout = "~/Views/Shared/_Layout.cshtml";
    }
    Layout = layout;
}
Adding the _ViewStart file in each of the directories

You can also set the default layout for a particular directory by putting the _ViewStart file in each of the directories with the required Layout information as shown below:

Defining Layout within each view on the top

@{
    Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
Returning Layout from ActionResult
public ActionResult Index()
{
    RegisterModel model = new RegisterModel();
    //TODO:
    return View("Index", "_AdminLayout", model);
}
What is the App_Start folder in ASP.NET MVC?

App_Start folder has been introduced in MVC4. It contains various configurations files like as   

BundleConfig.cs, FilterConfig.cs, RouteConfig.cs, WebApiConfig.cs for your application. All these settings are registered within the Application_Start method of Global.asax.cs file.      

BundleConfig.cs – This is used to create and register bundles for CSS and JS files. By default, various bundles are added in these files including jQuery, jQueryUI, jQuery Validation, Modernizr, and Site CSS.    

FIlterConfig.cs – This is used to register global MVC filters like error filters, action filters, etc. By default, it contains the HandleErrorAttribute filter.

RouteConfig.cs – This is used to register various route patterns for your ASP.NET MVC application. By default, one route is registered here named as Default Route.

WebApiConfig.cs – This is used to register various WEB API routes like ASP.NET MVC, as well as set any additional WEB API configuration settings.

What are the different ways of returning/rendering a view in ASP.NET MVC?

This is one of the Frequently asked ASP.NET MVC interview questions and answers. There are four different ways of returning/rendering a view in ASP.NET MVC as given below:

  1. Return View() – This tells MVC to generate HTML to be displayed for the specified view and sends it to the browser. This acts as a Server.Transfer() in ASP.NET WebForm.
  2. 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. This acts like Response.Redirect() in ASP.NET WebForm.

Moreover, RedirectToAction constructs a redirect URL to a specific action/controller in your application and use the routing table to generate the correct URL. RedirectToAction causes the browser to receive a 302 redirect within your application and gives you an easier way to work with your router table.

  1. Return Redirect() – This tells MVC to redirect to a specified URL instead of rendering HTML. In this case, the browser receives the redirect notification and make a new request for the specified URL. This also acts like a Response.Redirect() in ASP.NET WebForm. In this case, you have to specify the full URL to redirect.

Moreover, Redirect also causes the browser to receive a 302 redirect within your application, but you have to construct the URLs yourself.

  1. 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. This also make a new request like RedirectToAction().
Points to Remember:
  1. Return View doesn’t make a new request, it just renders the view without changing URLs in the browser’s address bar.
  2. The Return RedirectToAction makes a new request and URL in the browser’s address bar is updated with the generated URL by MVC.
  3. Return Redirect also makes a new request and URL in the browser’s address bar is updated, but you have to specify the full URL to redirect
  4. Between RedirectToAction and Redirect, best practice is to use RedirectToAction for anything dealing with your application actions/controllers. If you use Redirect and provide the URL, you’ll need to modify those URLs manually when you change the routing table.
  5. RedirectToRoute redirects to a specific route defined in the Route table.
What is Area in ASP.NET MVC?

Areas were introduced in Asp.net MVC2 which allows us to organize models, views, and controllers into separate functional sections of the application, such as administration, billing, customer support, and so on. This is very helpful in a large web application, where all the controllers, views, and models have a single set of folders and that becomes difficult to manage.

Each MVC area has its own folder structure which allows us to keep separate controllers, views, and models. This also helps the multiple developers to work on the same web application without interfering with one another.

How to register Area in ASP.NET MVC?

Before working with the area, make sure you have registered your area within the Application_Start method in Global.asax as shown below.

protected void Application_Start()
{
    //Register all application Areas 
    AreaRegistration.RegisterAllAreas();
}

Always remember the order of registering the Areas must be on top so that all of the settings, filters, and routes registered for the applications will also apply to the Areas.

What is Scaffolding?

We (developers) spent most of our time writing code for CRUD operations that are connecting to a database and performing operations like Create, Retrieve, Update and Delete. Microsoft introduces a very powerful feature called Scaffolding that does the job of writing CRUD operations code for us.

Scaffolding is basically a Code Generation framework. Scaffolding Engine generates basic controllers as well as views for the models using Microsoft’s T4 template. Scaffolding blends with Entity Framework and creates the instance for the mapped entity model and generates code of all CRUD Operations. Further, we can edit or customize this auto-generated code according to our needs. As a result, we get the basic structure for a tedious and repetitive task.

Following are the few advantages of Scaffolding:

  1. RAD approach for data-driven web applications.
  2. Minimal effort to improve the Views.
  3. Data Validation based on database schema.
  4. Easily created filters for the foreign key or boolean fields.
What are the differences between ViewData, ViewBag, TempData, and Session?

This is one of the Frequently asked ASP.NET MVC interview questions and answers. In ASP.NET MVC there are three ways – ViewData, ViewBag, and TempData to pass data from the controller to view and in the next request. Like WebForm, we can also use Session to persist data during a user session.

ViewData in ASP.NET MVC

public ViewDataDictionary ViewData { get; set; }

  1. ViewData is a dictionary object that is derived from ViewDataDictionary class.
  2. The ViewData is used to pass data from the controller to the corresponding view.
  3. Its life lies only during the current request.
  4. If redirection occurs then its value becomes null.
  5. It’s required typecasting for getting data and check for null values to avoid the error.
ViewBag in ASP.NET MVC

public Object ViewBag { get; set;}

  1. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  2. Basically, it is a wrapper around the ViewData and also used to pass data from the controller to the corresponding view.
  3. Its life also lies only during the current request.
  4. If redirection occurs then its value becomes null.
  5. It doesn’t require typecasting for getting data.
TempData in ASP.NET MVC

public TempDataDictionary TempData { get; set; }

  1. TempData is a dictionary object that is derived from the TempDataDictionary class and stored in a short life session.
  2. TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
  3. Its life is very short and lies only until the target view is fully loaded.
  4. It’s required typecasting for getting data and check for null values to avoid the error.
  5. It’s used to store only one time messages like error messages, validation messages.
Session in ASP.NET MVC

public HttpSessionStateBase Session { get;set; }

  1. In ASP.NET MVC, Session is a property of Controller class whose type is HttpSessionStateBase.
  2. The session is also used to pass data within the ASP.NET MVC application and Unlike TempData, it persists data for a user session until it is timeout (by default session timeout is 20 minutes).
  3. A session is valid for all requests, not for a single redirect.
  4. It’s also required typecasting for getting data and check for null values to avoid the error.
How to control Session behavior in ASP.NET MVC?

This is one of the Frequently asked ASP.NET MVC interview questions and answers. By default, ASP.NET MVC support session state. The session is used to store data values across requests. Whether you store some data values within the session or not ASP.NET MVC must manage the session state for all the controllers in your application that is time-consuming. Since, the session is stored in the server-side and consumes server memory, hence it also affects your application performance.

If some of the controllers of your ASP.NET MVC application are not using session state features, you can disable session for those controllers and can gain slight performance improvement of your application. You can simplify the session state for your application by using available options for the session state.

SessionState attribute provides you more control over the behavior of session-state by specifying the value of SessionStateBehavior enumeration as shown below:

Value          Description
Default       => The default ASP.NET behavior is used to determine the session state behavior.
Disabled    => Session state is disabled entirely.
ReadOnly  => Read-only session state behavior is enabled.
Required   => Full read-write session state behavior is enabled.

How is TempData related to Session in ASP.NET MVC?

In ASP.NET MVC, TempData uses a session state for storing the data values across requests. Hence, when you will disable the session state for the controller, it will throw the exception.

In the next article, I am going to discuss the Most Frequently asked ASP.NET MVC Routing Interview Questions and Answers. Here, in this article, I try to explain the most frequently asked ASP.NET MVC Interview questions and answers. I hope you enjoy this ASP.NET MVC Interview Questions and Answers article.  I would like to have your feedback. Please post your feedback, question, or comments about this ASP.NET MVC Interview Questions and Answers article.

Leave a Reply

Your email address will not be published. Required fields are marked *