ASP.NET Core 1.0 MVC View

View is said to be the UI part of a web application. In simple terms, it can be called the HTML Template which is used to generate final HTML. It is important to note that Razor code is executed on the server side to generate final HTML of a page with the help of Razor Engine. ASP.NET Core MVC Views has .cshtml extension (for C# ) and by default these files are stored in Views folder. Generally, controller has its own folder with views for related controller action methods.
mvc
By use, there are the  following main types of views,

  • Action Specific Views
  • Partial Views
  • Layouts
  • Special View

Action Specific Views

Action Specific Views are called from some action method and they are generally stored in view folder related controller and by default have same name as action method. We can call views of different names by specifying view name and from different folders by specifying full path from an action method. Generally full qualified path is like “~/Views/FolderPath/ViewName.cshtml” or with relative path “../FolderPath/ViewName.cshtml”.

Partial views

Partial Views are said to be reusable components and very similar to web control in ASP.Net Web Forms. They can also be used to decompose complex structures into smaller parts. But main purpose of them is reusability. Partial View is rendered within another view. Partial view has same extension as view .cshtml and it is not required but a practice to start partical view with underscore (_). Technically, partial view is the same as normal view but we make its Layout null. Furthermore, special views like _ViewStart are not executed for partial views.

We can add partial View into a view with @Html.Partial(“_ViewName”), while partial view can have relative or full qualified path. And if we have strongly typed partial view, then we may add partial view with @Html.Partial(“_ViewName”, dataModel). It is important to note that partial views can be nested. So we can add a partial view in another partial view. Within each view or partial view, relative paths are always relative to that view, not the root or parent view. We are not allowed to have partial views loop cycle (circular nesting).

Layouts

Layout Views are said to be a main structure and they are very similar to Master Page in ASP.NET Web Forms. Layout View defines main structure of a web application and may contain header, menu, footer and page content area as per requirements. They facilitate us to define and handle all these at one place. It is common to have at least one layout view, but we can have more than one layout views to meet different requirements. For example, we can have different layouts for front office and back office. Or to have different layout for popups. It is customary to have layout view as “_Layout.cshtml” in Shared Folder of Views. We set layout of a page with following statement in view or in _ViewStart.cshtml.

  1. @{   
  2. Layout = “_Layout”;   
  3. }   
Layout View contains special tag @RenderBody() in which main called view is added and @RenderSection() which specifies section to be rendered in view. We will discuss sections in detail in future sessions.

Special View

Like Layout View, ASP.NET has couple of other special views,

 

  • _ViewImports.cshtml
  • _ViewStart.cshtml

_ViewImports.cshtml

_ViewImports view is used to perform activities like: importing namespaces or performing dependency injection, shared directive. Generally, we have _ViewImports at the root Views folder, but we can have as many as required. For example, we can add _ViewImports view in each folder. In this case current folder settings are added to settings from upper folder. And in case of conflict settings from from nearest _ ViewImports view get preference. The _ViewImports file supports the following directives.

  • @addTagHelper
  • @removeTagHelper
  • @tagHelperPrefix
  • @using
  • @model
  • @inherits
  • @inject

_ViewStart.cshtml

_ViewStart.cshtml is used to execute common tasks like setting Layout View. The statements listed in _ViewStart.cshtml are run before every view except layouts, and partial views. Generally, _ViewStart.cshtml is located in the Views folder. Like _ViewImports.cshtml every folder can have _ViewStart.cshtml. These are executed from parent to child in sequence.

View Discovery

View Discovery in the process to identify the viewed called by an action method or a partial view during rendering of final Html. If a view name is not specified or name without path is specified then this process determines which view file will be used based on predefined steps. For example, when an action returns the View without view name then action name is used as the view name. Similarly, runtime looks for a controller-specific view first, then looks for matching view name in the Shared folder. And when view is specified with a full qualified path then only specific view file is used.

View Categorization based on Model

We can categorize Views on bases of Model or data manipulation as following,

  • Loosely Typed or Type Less Views
  • Strongly Typed Views
  • Dynamic Views

Loosely Typed or Type Less Views

We can pass data to views using loosely typed data collections: ViewData and ViewBag.

ViewData

ViewData is a dictionary object accessed through string keys. We can store and retrieve objects in it, and we may need to cast them to a specific type. We can use ViewData to pass data from a controller to views, as well as within views (and partial views and layouts). String data can be stored and used directly, without the need for a cast.

In Action Method

  1. public IActionResult About() {  
  2.     ViewData["Message"] = "Your application description page.";  
  3.     return View();  
  4. }  
In View
  1. @{   
  2. ViewData["Title"] = "About";   
  3. }   
  4. <h2>@ViewData["Title"].</h2>   
  5. <h3>@ViewData["Message"]</h3>   
ViewBag

The ViewBag property is a wrapper around ViewData that provides a dynamic view over that collection. It is not a separate collection. The ViewBag objects provides dynamic access to the objects stored in ViewData. This can be more convenient to work with, since it doesn’t require casting.

In Action Method
  1. public IActionResult Contact()  
  2. {  
  3.     ViewBag.Message = "Your contact page.";  
  4.     return View();  
  5. }  
In View
  1. @{   
  2. ViewBag.Title = "Contact";   
  3. }   
  4. <h2>@ViewBag.Title</h2>   
  5. <h3>@ViewBag.Message</h3>   
Which One to Use

Although ViewBag is just a wraper on ViewData collection and we can mix and match between ViewData and ViewBag without any issue, yet it is better to use one approach in a project.

Strongly Typed Views

Strongly Typed View has a specific model type in the view, and it is mapped to an instance of this type passed to the view from the action as parameter. We can specify a model for a view using the @model directive then the instance sent to the view can be accessed in a strongly-typed manner using @Model as object of specified type.It is highly practiced and is most recommended option to pass data as it gives lot of benefits like robustness, compilation protection over other approaches.

Although we can use any type as model, but it is recommend to use Plain Old CLR Object (POCO) ViewModels. Please refer to ASP.NET Core 1.0 MVC Model for more details about Model and ViewModel,

Dynamic Views

Dynamic Views are a hybrid of both Strongly Typed and Loosely Typed Views. In this kind of view model is not declared but has a model instance passed to them. But @model and its properties can be used in view dynamically. In this case we don't have compilation protection or IntelliSense. If the property doesn’t exist, then application crashes at runtime.

Additional Features

There are many other features related with Views like following, but we may discuss them in different sessions in future,

 

  • Tag Helper
  • HTML Helper
  • View Scaffolding
  • Razor Engine

Further Reading

For further details, please refer to official documentation at MSDN.