MVC Partial Views and Sessions Interview Questions

ASP.NET MVC Partial Views and Sessions Interview Questions

In this article, I will discuss Most Frequently asked MVC Partial Views and Sessions Interview Questions and answers.

What is Partial View in ASP.NET MVC?

A partial view is like as user control in ASP.NET Web forms that are used for code re-usability. Partial views help us to reduce code duplication. Hence partial views are reusable views like as 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 specify 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 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 in a layout page can be defined by using the following code.

@section header{ <h1>Header Content</h1>

}

You can render 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?

RenderBody method exists in the Layout page to render child page/view. It is just like the ContentPlaceHolder on 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 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.

protected void Application_Start()
{
    //other code has been removed for clarity //disable optimization
    System.Web.Optimization.BundleTable.EnableOptimizations = false;
}
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 this files including jQuery, jQueryUI, jQuery Validation, Modernizr, and Site CSS.    

FIlterConfig.cs – This is used to register global MVC filters like error filters, actions 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 as 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?

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 like as 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 as Response.Redirect() in ASP.NET WebForm.

Moreover, RedirectToAction constructs a redirect URL to a specific action/controller in your application and use the route 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 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 as Response.Redirect() in ASP.NET WebForm. In this case, you have to specify the full URL to redirect.

Moreover, Redirect also cause 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().
Note:
  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 route table.
  5. RedirectToRoute redirects to a specific route defined in the Route table.
What is Area in ASP.NET MVC?

Areas was introduced in Asp.net MVC2 which allow 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 interfere with one another.

How to register Area in ASP.NET MVC?

Before working with 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 Child action and how to invoke it?

Child actions are useful for creating reusable widgets which could be embedded into 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 child attribute and has its independent MVC lifecycle from the parent view. Also, an action which has a child 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 is Scaffolding?

We (developers) spent most of our time writing code for CRUD operations that is 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 need. 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 among ViewData, ViewBag, TempData, and Session?

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

ViewData

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 controller to the corresponding view.
  3. Its life lies only during the current request.
  4. If redirection occurs then its value becomes null.
  5. Its required typecasting for getting data and check for null values to avoid error.
ViewBag

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 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

public TempDataDictionary TempData { get; set; }

  1. TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives 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 error.
  5. It’s used to store only one time messages like error messages, validation messages.
Session

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 error.
How to control Session behavior in ASP.NET MVC?

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 on the server side and consumes server memory, hence it also affect 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 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 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 as shown below:

SUMMARY

In this article, I try to explain most frequently asked MVC Partial Views and Sessions Interview Questions and Answers. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Follow Us

Leave a Reply

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