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.
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:
You can use a layout to define a common template for your site. A layout can be declared at the top of view as:
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.
You can render the above-defined section header on the content page as given below:
By default, sections are mandatory. To make sections optional just provides the second parameter value as false, which is a Boolean value.
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.
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.
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.
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.
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:
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
Returning Layout from ActionResult
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:
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.
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:
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
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:
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.
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.
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:
- 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.
- 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.
- 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.
- 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().
- Return View doesn’t make a new request, it just renders the view without changing URLs in the browser’s address bar.
- The Return RedirectToAction makes a new request and URL in the browser’s address bar is updated with the generated URL by MVC.
- 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
- 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.
- RedirectToRoute redirects to a specific route defined in the Route table.
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:
- RAD approach for data-driven web applications.
- Minimal effort to improve the Views.
- Data Validation based on database schema.
- Easily created filters for the foreign key or boolean fields.
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; }
- ViewData is a dictionary object that is derived from ViewDataDictionary class.
- The ViewData is used to pass data from the controller to the corresponding view.
- Its life lies only during the current request.
- If redirection occurs then its value becomes null.
- It’s required typecasting for getting data and check for null values to avoid the error.
public Object ViewBag { get; set;}
- ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
- Basically, it is a wrapper around the ViewData and also used to pass data from the controller to the corresponding view.
- Its life also lies only during the current request.
- If redirection occurs then its value becomes null.
- It doesn’t require typecasting for getting data.
public TempDataDictionary TempData { get; set; }
- TempData is a dictionary object that is derived from the TempDataDictionary class and stored in a short life session.
- TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
- Its life is very short and lies only until the target view is fully loaded.
- It’s required typecasting for getting data and check for null values to avoid the error.
- It’s used to store only one time messages like error messages, validation messages.
public HttpSessionStateBase Session { get;set; }
- In ASP.NET MVC, Session is a property of Controller class whose type is HttpSessionStateBase.
- 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).
- A session is valid for all requests, not for a single redirect.
- It’s also required typecasting for getting data and check for null values to avoid the error.
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.
0 comments:
Post a Comment
If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.