Monday, 19 September 2016

ASP.NET Core 1.0 MVC View

View is said to be UI part of a web application. In simple, it can be called HTML Template which is used to generate final HTML. It is important to note that Razor code is executed server side to generate final HTML of a page with 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.



By use, there following main types of views:
  • Action Specific Views
  • Partial Views
  • Layouts
  • Special View

Action Specific Views

Action Specific View are called from some action method and they are generally stored in view folder related controller and by default have same name as of action method. We can call views of different name by specifying view name and from different folder 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”. Please refer to ASP.NET Core 1.0 MVC Controller for more details about Controllers.

Partial views

Partial View 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 views has same extension like view .cshtml and it is not required but a practice to start partical view with underscore (_). Technically, partial view is 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 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.

 @{  
  Layout = “_Layout”;  
 }  

Layout view contain 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   
 public IActionResult About()  
 {  
   ViewData["Message"] = "Your application description page.";  
   return View();  
 }  
 In View  
 @{  
   ViewData["Title"] = "About";  
 }  
 <h2>@ViewData["Title"].</h2>  
 <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   
 public IActionResult Contact()  
 {  
   ViewBag.Message = "Your contact page.";  
   return View();  
 }  
 In View  
 @{  
   ViewBag.Title = "Contact";  
 }  
 <h2>@ViewBag.Title</h2>  
 <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 a 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 hybrid of both Strongly Typed and Loosely Typed Views. In this kind of view model is not declared but have a model instance passed to them. But @model and it's 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: https://docs.asp.net/en/latest/mvc/views/index.html.

4 comments:

  1. The blog gave me idea about ASP.NET Core 1.0 MVC View My sincere thanks for sharing this post Please Continue to share this kind of post
    Dot Net Training in Chennai

    ReplyDelete
  2. nice blog has been shared by you. before i read this blog i didn't have any knowledge about this but now i got some knowledge. so keep on sharing such kind of an interesting blogs.
    dot net training in chennai

    ReplyDelete
  3. Nice post. haven't try this to see work. But I guess this works. Thanks for posting. keep posting.. thank you...
    Big data Analytics Training in Chennai | Software Testing Training in Chennai

    ReplyDelete
  4. Nice and good blog to read.... really i gathered some information thanks for sharing..Diploma Project Center in Chennai | Diploma Project Center in Velachery

    ReplyDelete