Views Interview Questions in ASP.NET MVC

Views Interview Questions in ASP.NET MVC

In this article, I will discuss Most Frequently asked Views Interview Questions in ASP.NET MVC with answers. Please read our previous article where we discussed the most frequently asked View Engine and HTML Helpers Interview Questions with Answers in ASP.NET MVC Application. As part of this article, we are going to discuss the following Views Interview Questions in ASP.NET MVC Application with answers.

  1. What are Partial Views in ASP.NET MVC and it’s needed?
  2. What are the Layouts in ASP.NET MVC
  3. What are Sections in ASP.NET MVC?
  4. What are RenderBody and RenderPage in ASP.NET MVC?
  5. What are the Styles.Render and Scripts.Render?
  6. How to enable and disable optimizations in ASP.NET MVC?
  7. What is _ViewStart?
  8. What are the different ways of rendering layout in ASP.NET MVC?
  9. What is the App_Start folder in ASP.NET MVC?
  10. What are the different ways of returning/rendering a view in ASP.NET MVC?
  11. What is Area in ASP.NET MVC?
  12. How to register Area in ASP.NET MVC?
  13. What is Scaffolding?
  14. What are the differences between ViewData, ViewBag, TempData, and Session?
  15. How to control Session behavior in ASP.NET MVC?
  16. How is TempData related to Session in ASP.NET MVC?
What are Partial Views in ASP.NET MVC and it’s needed?

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?

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?

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?

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?

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 as shown below:

In the next article, I am going to discuss the most frequently asked Action Methods Interview Questions in ASP.NET MVC with Answers. Here, in this article, I try to explain the most frequently asked Views Interview Questions in ASP.NET MVC Application with Answers. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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