SlideShare a Scribd company logo
.NET Core + ASP.NET Core Training Course
Session 11
.NET Core
What we learned?
Session 6 ~ 10 Overview
• ASP.NET Core Basics
• Middleware in ASP.NET core
• Controllers
• Action Filters
• Routing
• Model Binding
• Model Validation
.NET Core
What we’ll learn today?
Session 11 Agenda
• Views
.NET Core
Views
Views
ASP.NET MVC Core controllers can return formatted results using views.
The view encapsulates the presentation details of the user’s interaction with the
app. Views are HTML templates with embedded code that generate content to send
to the client. Views use Razor syntax, which allows code to interact with HTML with
minimal code or ceremony.
.NET Core
Views
Views
views are .cshtml files stored by default in a Views folder within the application.
Typically, each controller will have its own folder, in which are views for specific
controller actions.
Views provide separation of concerns within an MVC app, encapsulating user
interface level markup separately from business logic. ASP.NET MVC views use Razor
syntax to make switching between HTML markup and server side logic painless.
.NET Core
Creating a View
Views - Creating
Views that are specific to a controller are created in the Views/[ControllerName]
folder.
Views that are shared among controllers are placed in the /Views/Shared folder.
.NET Core
Creating a View
Views - Creating
Razor code is denoted by the @ symbol. C# statements are run within Razor code
blocks set off by curly braces ({ })
How do Controllers Specify Views?
Views are typically returned from actions as a ViewResult. Your action method can
create and return a ViewResult directly, but more commonly if your controller
inherits from Controller, you’ll simply use the View helper method. You can
optionally specify a view to return, as well as a model object to pass to the view.
.NET Core
View Discovery
Views - Discovery
When an action returns a view, a process called view discovery takes place.
This process determines which view file will be used. Unless a specific view file is
specified, the runtime looks for a controller-specific view first, then looks for
matching view name in the Shared folder.
view discovery searches for a matching view file in:
1. Views/<ControllerName>/<ViewName>.cshtml
2. Views/Shared/<ViewName>.cshtml
.NET Core
View Discovery
Views - Discovery
A view file path can be provided, instead of a view name. In this case, the .cshtml
extension must be specified as part of the file path. The path should be relative to
the application root (and can optionally start with “/” or “~/”). For example:
return View("Views/Home/About.cshtml");
customize the default convention regarding where views are located within the app
by using a custom IViewLocationExpander.
.NET Core
Razor View Names
Views
View names may be case sensitive depending on the underlying file system. For
compatibility across operating systems, always match case between controller and
action names and associated view folders and filenames.
.NET Core
Passing Data to Views
Views
You can pass data to views using several mechanisms. The most robust approach is
to specify a model type in the view (commonly referred to as a viewmodel, to
distinguish it from business domain model types), and then pass an instance of this
type to the view from the action.
It’s recommend to use a model or view model to pass data to a view. This allows the
view to take advantage of strong type checking. You can specify a model for a view
using the @model directive
.NET Core
Passing Data to Views
Views
Once a model has been specified for a view, the instance sent to the view can be
accessed in a strongly-typed manner using @Model as shown above.
.NET Core
Passing Data to Views
Views
To provide an instance of the model type to the view, the controller passes it as a
parameter
There are no restrictions on the
types that can be provided to a
view as a model. We recommend
passing Plain Old CLR Object
(POCO) view models with little
or no behavior, so that business
logic can be encapsulated
elsewhere in the app.
.NET Core
Loosely Typed Data
Views
In addition to strongly typed views, all views have access to a loosely typed
collection of data. This same collection can be referenced through either the
ViewData or ViewBag properties on controllers and views.
The ViewBag property is a wrapper around ViewData that provides a dynamic view
over that collection. It is not a separate collection.
.NET Core
Loosely Typed Data
Views
ViewData is a dictionary object accessed through string keys. You can store and
retrieve objects in it, and you’ll need to cast them to a specific type when you
extract them. You 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.
.NET Core
Loosely Typed Data
Views
.NET Core
Loosely Typed Data
Views
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. The
same example as above, using ViewBag instead of a strongly typed address
instance in the view:
.NET Core
Dynamic Views
Views
Views that do not declare a model type but have a model instance passed to them
can reference this instance dynamically. For example, if an instance of Address is
passed to a view that doesn’t declare an @model, the view would still be able to
refer to the instance’s properties dynamically.
This feature can offer some flexibility, but does not offer any compilation
protection or IntelliSense. If the property doesn’t exist, the page will fail at
runtime.
.NET Core
Partial Views
Views - Partial Views
ASP.NET Core MVC supports partial views, which are useful when you have
reusable parts of web pages you want to share between different views.
A partial view is a view that is rendered within another view. The HTML output
generated by executing the partial view is rendered into the calling (or parent)
view. Like views, partial views use the .cshtml file extension.
.NET Core
When Should I Use Partial Views?
Views - Partial Views
Partial views are an effective way of breaking up large views into smaller
components. They can reduce duplication of view content and allow view
elements to be reused.
Common layout elements should be specified in _Layout.cshtml. Non-layout
reusable content can be encapsulated into partial views.
.NET Core
When Should I Use Partial Views?
Views - Partial Views
If you have a complex page made up of several logical pieces, it can be helpful
to work with each piece as its own partial view.
Each piece of the page can be viewed in isolation from the rest of the page, and
the view for the page itself becomes much simpler since it only contains the
overall page structure and calls to render the partial views.
.NET Core
Declaring Partial Views
Views - Partial Views
You can have a view that is returned directly from a controller’s ViewResult, and
the same view can be used as a partial view.
The main difference between how a view and a partial view are rendered is that
partial views do not run _ViewStart.cshtml (while views do - learn more about
_ViewStart.cshtml in Layout).
.NET Core
Referencing a Partial View
Views - Partial Views
From within a view page, there are several ways in which you can render a partial
view. The simplest is to use Html.Partial, which returns an IHtmlString and can be
referenced by prefixing the call with @:
@Html.Partial("AuthorPartial")
The PartialAsync method is available for partial views containing asynchronous
code (although code in views is generally discouraged):
@await Html.PartialAsync("AuthorPartial")
.NET Core
Referencing a Partial View
Views - Partial Views
You can render a partial view with RenderPartial. This method doesn’t return a
result; it streams the rendered output directly to the response. Because it doesn’t
return a result, it must be called within a Razor code block (you can also call
RenderPartialAsync if necessary):
@{
Html.RenderPartial("AuthorPartial");
}
.NET Core
Partial View Discovery
Views - Partial Views
.NET Core
Referencing a Partial View
Views - Partial Views
If desired, you can have different partial views with the same name in different
view folders. When referencing the views by name (without file extension), views
in each folder will use the partial view in the same folder with them. You can also
specify a default partial view to use, placing it in the Shared folder. This view will
be used by any views that don’t have their own copy of the partial view in their
folder. In this way, you can have a default partial view (in Shared), which can be
overridden by a partial view with the same name in the same folder as the
parent view.
.NET Core
Referencing a Partial View
Views - Partial Views
Partial views can be chained. That is, a partial view can call another partial view
(as long as you don’t create a loop). Within each view or partial view, relative
paths are always relative to that view, not the root or parent view.
.NET Core
Accessing Data From Partial Views
Views - Partial Views
When a partial view is instantiated, it gets a copy of the parent view’s ViewData
dictionary. Updates made to the data within the partial view are not persisted to
the parent view. ViewData changed in a partial view is lost when the partial view
returns.
You can pass an instance of ViewDataDictionary to the partial view:
@Html.Partial("PartialName", customViewData)
.NET Core
Accessing Data From Partial Views
Views - Partial Views
You can also pass a model into a partial view. This can be the page’s view model,
or some portion of it, or a custom object. Simply pass in the model as the
second parameter when calling Partial/PartialAsync or
RenderPartial/RenderPartialAsync:
@Html.Partial("PartialName", viewModel)
You can pass an instance of ViewDataDictionary and a view model to a partial
view:
@Html.Partial("PartialName", viewModel, customViewData)
.NET Core
What is a Layout?
Layout
Most web apps have a common layout that provides the user with a consistent
experience as they navigate from page to page. The layout typically includes
common user interface elements such as the app header, navigation or menu
elements, and footer.
.NET Core
What is a Layout?
Layout
By convention, the default layout for an ASP.NET app is named _Layout.cshtml.
Razor views have a Layout property. Individual views specify a layout by setting
this property:
@{
Layout = "_Layout";
}
.NET Core
What is a Layout?
Layout
The layout specified can use a full path (example: /Views/Shared/_Layout.cshtml)
or a partial name (example: _Layout).
When a partial name is provided, the Razor view engine will search for the
layout file using its standard discovery process.
The controller-associated folder is searched first, followed by the Shared folder.
This discovery process is identical to the one used to discover partial views.
.NET Core
Using Layout
Layout
By default, every layout must call RenderBody. Wherever the call to RenderBody
is placed, the contents of the view will be rendered.
A layout can optionally reference one or more sections, by calling
RenderSection. Sections provide a way to organize where certain page elements
should be placed. Each call to RenderSection can specify whether that section is
required or optional. If a required section is not found, an exception will be
thrown.
.NET Core
Using Layout
Layout
An example @section definition in a view:
@section Scripts {
<script type="text/javascript" src="/scripts/main.js"></script>
}
Sections defined in a view are available only in its immediate layout page. They
cannot be referenced from partials, view components, or other parts of the view
system.
.NET Core
Using Layout - Ignoring sections
Layout
By default, the body and all sections in a content page must all be rendered by
the layout page. The Razor view engine enforces this by tracking whether the
body and each section have been rendered.
To instruct the view engine to ignore the body or sections, call the IgnoreBody
and IgnoreSection methods.
The body and every section in a Razor page must be either rendered or ignored.
.NET Core
Using Layout - Importing Shared Directives
Layout
Views can use Razor directives to do many things, such as importing namespaces or
performing dependency injection. Directives shared by many views may be specified in
a common _ViewImports.cshtml file. The _ViewImports file supports the following
directives:
• @addTagHelper
• @removeTagHelper
• @tagHelperPrefix
• @using
• @model
• @inherits
• @inject
.NET Core
Using Layout - _ViewImports.cshtml
Layout
A sample _ViewImports.cshtml file:
@using WebApplication1
@using WebApplication1.Models
@using WebApplication1.Models.AccountViewModels
@using WebApplication1.Models.ManageViewModels
@using Microsoft.AspNetCore.Identity
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
.NET Core
Using Layout - _ViewImports.cshtml
Layout
The _ViewImports.cshtml file for an ASP.NET Core MVC app is typically placed in
the Views folder. A _ViewImports.cshtml file can be placed within any folder, in
which case it will only be applied to views within that folder and its subfolders.
_ViewImports files are processed starting at the root level, and then for each
folder leading up to the location of the view itself, so settings specified at the
root level may be overridden at the folder level.
.NET Core
Using Layout - _ViewImports.cshtml
Layout
For example, if a root level _ViewImports.cshtml file specifies @model and
@addTagHelper, and another _ViewImports.cshtml file in the controller-
associated folder of the view specifies a different @model and adds another
@addTagHelper, the view will have access to both tag helpers and will use the
latter @model.
.NET Core
Using Layout - _ViewImports.cshtml
Layout
If multiple _ViewImports.cshtml files are run for a view, combined behavior of
the directives included in the ViewImports.cshtml files will be as follows:
@addTagHelper, @removeTagHelper: all run, in order
@tagHelperPrefix: the closest one to the view overrides any others
@model: the closest one to the view overrides any others
@inherits: the closest one to the view overrides any others
@using: all are included; duplicates are ignored
@inject: for each property, the closest one to the view overrides any others with
the same property name
.NET Core
Running Code Before Each View
Layout
If you have code you need to run before every view, this should be placed in the
_ViewStart.cshtml file. By convention, the _ViewStart.cshtml file is located in the
Views folder. The statements listed in _ViewStart.cshtml are run before every full
view (not layouts, and not partial views). Like ViewImports.cshtml,
_ViewStart.cshtml is hierarchical.
.NET Core
View Components
View Components
New to ASP.NET Core MVC, view components are similar to partial views, but
they are much more powerful. View components don’t use model binding, and
only depend on the data you provide when calling into it. A view component:
• Renders a chunk rather than a whole response
• Includes the same separation-of-concerns and testability benefits found
between a controller and view
• Can have parameters and business logic
• Is typically invoked from a layout page
.NET Core
View Components
View Components
View Components are intended anywhere you have reusable rendering logic
that is too complex for a partial view, such as:
• Dynamic navigation menus
• Tag cloud (where it queries the database)
• Login panel
• Shopping cart
• Recently published articles
• Sidebar content on a typical blog
• A login panel that would be rendered on every page and show either the links to
log out or log in, depending on the log in state of the user
.NET Core
View Components
View Components
A view component consists of two parts, the class (typically derived from
ViewComponent) and the result it returns (typically a view).
Like controllers, a view component can be a POCO, but most developers will
want to take advantage of the methods and properties available by deriving
from ViewComponent.
.NET Core
Creating a view component
View Components
A view component class can be created by any of the following:
• Deriving from ViewComponent
• Decorating a class with the [ViewComponent] attribute, or deriving from a
class with the [ViewComponent] attribute
• Creating a class where the name ends with the suffix ViewComponent
Like controllers, view components must be public, non-nested, and non-abstract
classes. The view component name is the class name with the “ViewComponent”
suffix removed. It can also be explicitly specified using the
ViewComponentAttribute.Name property.
.NET Core
Creating a view component
View Components
A view component class:
• Fully supports constructor dependency injection
• Does not take part in the controller lifecycle, which means you can’t use
filters in a view component
.NET Core
View component methods
View Components
A view component defines its logic in an InvokeAsync method that returns an
IViewComponentResult.
Parameters come directly from invocation of the view component, not from
model binding. A view component never directly handles a request. Typically a
view component initializes a model and passes it to a view by calling the View
method.
.NET Core
View component methods
View Components
• Define an InvokeAsync` method that returns an IViewComponentResult
• Typically initializes a model and passes it to a view by calling the
ViewComponent View method
• Parameters come from the calling method, not HTTP, there is no model
binding
• Are not reachable directly as an HTTP endpoint, they are invoked from your
code (usually in a view). A view component never handles a request
• Are overloaded on the signature rather than any details from the current
HTTP request
.NET Core
View components - View search path
View Components
The runtime searches for the view in the following paths:
• Views/<controller_name>/Components/<view_component_name>/<view_na
me>
• Views/Shared/Components/<view_component_name>/<view_name>
The default view name for a view component is Default, which means your view
file will typically be named Default.cshtml. You can specify a different view name
when creating the view component result or when calling the View method.
.NET Core
View components - View search path
View Components
We recommend you name the view file Default.cshtml and use the
Views/Shared/Components/<view_component_name>/<view_name> path.
.NET Core
Invoking a view component
View Components
To use the view component, call @Component.InvokeAsync("Name of view
component", <anonymous type containing parameters>) from a view. The
parameters will be passed to the InvokeAsync method.
In the following, the InvokeAsync method is called with two parameters:
@await Component.InvokeAsync("PriorityList", new { maxPriority = 2, isDone =
false })
.NET Core
Invoking a view component directly from a controller
View Components
View components are typically invoked from a view, but you can invoke them
directly from a controller method. While view components do not define
endpoints like controllers, you can easily implement a controller action that
returns the content of a ViewComponentResult.
In this example, the view component is called directly from the controller:
public IActionResult IndexVC()
{
return ViewComponent("PriorityList", new { maxPriority = 3, isDone = false });
}
.NET Core
Creating a simple view component demo
View Components
.NET Core
Creating a simple view component demo
View Components
Notes on the code:
• View component classes can be contained in any folder in the project.
• Because the class name PriorityListViewComponent ends with the suffix
ViewComponent, the runtime will use the string “PriorityList” when
referencing the class component from a view. I’ll explain that in more detail
later.
.NET Core
Creating a simple view component demo
View Components
Notes on the code:
• The [ViewComponent] attribute can change the name used to reference a
view component. For example, we could have named the class XYZ, and
applied the ViewComponent attribute:
[ViewComponent(Name = "PriorityList")]
public class XYZ : ViewComponent
.NET Core
Injecting Services Into Views
Injecting Services Into Views
ASP.NET Core supports dependency injection into views. This can be useful for
view-specific services, such as localization or data required only for populating
view elements.
You can inject a service into a view using the @inject directive. You can think of
@inject as adding a property to your view, and populating the property using DI.
.NET Core
Injecting Services Into Views
Injecting Services Into Views
The syntax for @inject:
@inject <type> <name>
.NET Core
Injecting Services Into Views
Injecting Services Into Views
The summary is populated from the injected StatisticsService. This service is
registered for dependency injection in ConfigureServices in Startup.cs:
.NET Core
Injecting Services Into Views
Injecting Services Into Views
View injection can be useful to populate options in UI elements, such as
dropdown lists.
Consider a user profile form that includes options for specifying gender, state,
and other preferences. Rendering such a form using a standard MVC approach
would require the controller to request data access services for each of these
sets of options, and then populate a model or ViewBag with each set of options
to be bound.
.NET Core
Injecting Services Into Views
Injecting Services Into Views
An alternative approach
injects services directly
into the view to obtain
the options. This
minimizes the amount of
code required by the
controller, moving this
view element
construction logic into
the view itself.
.NET Core
Injecting Services Into Views
Injecting Services Into Views
.NET Core
Injecting Services Into Views
Injecting Services Into Views
Overriding Services
In addition to injecting new services, this technique can also be used to override
previously injected services on a page. The figure below shows all of the fields
available on the page used in the first example:
.NET Core
Injecting Services Into Views
Injecting Services Into Views
Overriding Services
As you can see, the default fields include Html, Component, and Url (as well as
the StatsService that we injected). If for instance you wanted to replace the
default HTML Helpers with your own, you could easily do so using @inject:
.NET Core
Demo
Demo

More Related Content

What's hot

.NET Core, ASP.NET Core Course, Session 8
.NET Core, ASP.NET Core Course, Session 8.NET Core, ASP.NET Core Course, Session 8
.NET Core, ASP.NET Core Course, Session 8
aminmesbahi
 
.NET Core, ASP.NET Core Course, Session 19
 .NET Core, ASP.NET Core Course, Session 19 .NET Core, ASP.NET Core Course, Session 19
.NET Core, ASP.NET Core Course, Session 19
aminmesbahi
 
.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17
aminmesbahi
 
Share point review qustions
Share point review qustionsShare point review qustions
Share point review qustions
than sare
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9
aminmesbahi
 
.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6
aminmesbahi
 
.NET Core, ASP.NET Core Course, Session 2
.NET Core, ASP.NET Core Course, Session 2.NET Core, ASP.NET Core Course, Session 2
.NET Core, ASP.NET Core Course, Session 2
aminmesbahi
 
.NET Core, ASP.NET Core Course, Session 3
.NET Core, ASP.NET Core Course, Session 3.NET Core, ASP.NET Core Course, Session 3
.NET Core, ASP.NET Core Course, Session 3
aminmesbahi
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
Santosh Kumar Kar
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
Muthuselvam RS
 
Spring core
Spring coreSpring core
Spring core
Harshit Choudhary
 
Spring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 IntegrationSpring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 Integration
Majurageerthan Arumugathasan
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
Harshit Choudhary
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)
Amit Ranjan
 
Entity framework and how to use it
Entity framework and how to use itEntity framework and how to use it
Entity framework and how to use it
nspyre_net
 
Oracle Text in APEX
Oracle Text in APEXOracle Text in APEX
Oracle Text in APEX
Scott Wesley
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
Eric Nelson
 
Jspprogramming
JspprogrammingJspprogramming
Jspprogramming
Mallikarjuna G D
 
Maven
MavenMaven
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
John Lewis
 

What's hot (20)

.NET Core, ASP.NET Core Course, Session 8
.NET Core, ASP.NET Core Course, Session 8.NET Core, ASP.NET Core Course, Session 8
.NET Core, ASP.NET Core Course, Session 8
 
.NET Core, ASP.NET Core Course, Session 19
 .NET Core, ASP.NET Core Course, Session 19 .NET Core, ASP.NET Core Course, Session 19
.NET Core, ASP.NET Core Course, Session 19
 
.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17
 
Share point review qustions
Share point review qustionsShare point review qustions
Share point review qustions
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9
 
.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6
 
.NET Core, ASP.NET Core Course, Session 2
.NET Core, ASP.NET Core Course, Session 2.NET Core, ASP.NET Core Course, Session 2
.NET Core, ASP.NET Core Course, Session 2
 
.NET Core, ASP.NET Core Course, Session 3
.NET Core, ASP.NET Core Course, Session 3.NET Core, ASP.NET Core Course, Session 3
.NET Core, ASP.NET Core Course, Session 3
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
Spring core
Spring coreSpring core
Spring core
 
Spring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 IntegrationSpring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 Integration
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)
 
Entity framework and how to use it
Entity framework and how to use itEntity framework and how to use it
Entity framework and how to use it
 
Oracle Text in APEX
Oracle Text in APEXOracle Text in APEX
Oracle Text in APEX
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
 
Jspprogramming
JspprogrammingJspprogramming
Jspprogramming
 
Maven
MavenMaven
Maven
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
 

Similar to .NET Core, ASP.NET Core Course, Session 11

Asp.net c# MVC-5 Training-Day-2 of Day-9
Asp.net c# MVC-5 Training-Day-2 of Day-9Asp.net c# MVC-5 Training-Day-2 of Day-9
Asp.net c# MVC-5 Training-Day-2 of Day-9
AHM Pervej Kabir
 
Session 1
Session 1Session 1
Session 1
Asif Atick
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
Gigin Krishnan
 
MVC 4
MVC 4MVC 4
Mvc
MvcMvc
Stephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep DiveStephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep Dive
MicrosoftFeed
 
MVC Training Part 2
MVC Training Part 2MVC Training Part 2
MVC Training Part 2
Lee Englestone
 
ASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp PresentationASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp Presentation
buildmaster
 
Asp 1-mvc introduction
Asp 1-mvc introductionAsp 1-mvc introduction
Asp 1-mvc introduction
Fajar Baskoro
 
Dn D Custom 1
Dn D Custom 1Dn D Custom 1
Dn D Custom 1
ptalindstrom
 
Dn D Custom 1
Dn D Custom 1Dn D Custom 1
Dn D Custom 1
ptalindstrom
 
MVC
MVCMVC
MVC
akshin
 
J2EE pattern 5
J2EE pattern 5J2EE pattern 5
J2EE pattern 5
Naga Muruga
 
Adding a view
Adding a viewAdding a view
Adding a view
Nhan Do
 
Actionview
ActionviewActionview
Actionview
Amal Subhash
 
ASP.NET Identity
ASP.NET IdentityASP.NET Identity
ASP.NET Identity
Suzanne Simmons
 
MVC Training Part 1
MVC Training Part 1MVC Training Part 1
MVC Training Part 1
Lee Englestone
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPI
Eric Wise
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
Volkan Uzun
 
Spring mvc 2.0
Spring mvc 2.0Spring mvc 2.0
Spring mvc 2.0
Rudra Garnaik, PMI-ACP®
 

Similar to .NET Core, ASP.NET Core Course, Session 11 (20)

Asp.net c# MVC-5 Training-Day-2 of Day-9
Asp.net c# MVC-5 Training-Day-2 of Day-9Asp.net c# MVC-5 Training-Day-2 of Day-9
Asp.net c# MVC-5 Training-Day-2 of Day-9
 
Session 1
Session 1Session 1
Session 1
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
 
MVC 4
MVC 4MVC 4
MVC 4
 
Mvc
MvcMvc
Mvc
 
Stephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep DiveStephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep Dive
 
MVC Training Part 2
MVC Training Part 2MVC Training Part 2
MVC Training Part 2
 
ASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp PresentationASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp Presentation
 
Asp 1-mvc introduction
Asp 1-mvc introductionAsp 1-mvc introduction
Asp 1-mvc introduction
 
Dn D Custom 1
Dn D Custom 1Dn D Custom 1
Dn D Custom 1
 
Dn D Custom 1
Dn D Custom 1Dn D Custom 1
Dn D Custom 1
 
MVC
MVCMVC
MVC
 
J2EE pattern 5
J2EE pattern 5J2EE pattern 5
J2EE pattern 5
 
Adding a view
Adding a viewAdding a view
Adding a view
 
Actionview
ActionviewActionview
Actionview
 
ASP.NET Identity
ASP.NET IdentityASP.NET Identity
ASP.NET Identity
 
MVC Training Part 1
MVC Training Part 1MVC Training Part 1
MVC Training Part 1
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPI
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
 
Spring mvc 2.0
Spring mvc 2.0Spring mvc 2.0
Spring mvc 2.0
 

More from aminmesbahi

How to choose appropriate technology for product development - Persian Version
How to choose appropriate technology for product development - Persian VersionHow to choose appropriate technology for product development - Persian Version
How to choose appropriate technology for product development - Persian Version
aminmesbahi
 
How to choose appropriate technology for product development
How to choose appropriate technology for product developmentHow to choose appropriate technology for product development
How to choose appropriate technology for product development
aminmesbahi
 
Python + Machine Learning Course, Session 2
Python + Machine Learning Course, Session 2Python + Machine Learning Course, Session 2
Python + Machine Learning Course, Session 2
aminmesbahi
 
Python + Machine Learning Course, Session 1
Python + Machine Learning Course, Session 1Python + Machine Learning Course, Session 1
Python + Machine Learning Course, Session 1
aminmesbahi
 
.NET Core, ASP.NET Core Course, Session 5
.NET Core, ASP.NET Core Course, Session 5.NET Core, ASP.NET Core Course, Session 5
.NET Core, ASP.NET Core Course, Session 5
aminmesbahi
 
.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4
aminmesbahi
 
.NET Core, ASP.NET Core Course, Session 1
.NET Core, ASP.NET Core Course, Session 1.NET Core, ASP.NET Core Course, Session 1
.NET Core, ASP.NET Core Course, Session 1
aminmesbahi
 
A comparative study of process templates in team
A comparative study of process templates in teamA comparative study of process templates in team
A comparative study of process templates in team
aminmesbahi
 
SQL server 2016 New Features
SQL server 2016 New FeaturesSQL server 2016 New Features
SQL server 2016 New Features
aminmesbahi
 

More from aminmesbahi (9)

How to choose appropriate technology for product development - Persian Version
How to choose appropriate technology for product development - Persian VersionHow to choose appropriate technology for product development - Persian Version
How to choose appropriate technology for product development - Persian Version
 
How to choose appropriate technology for product development
How to choose appropriate technology for product developmentHow to choose appropriate technology for product development
How to choose appropriate technology for product development
 
Python + Machine Learning Course, Session 2
Python + Machine Learning Course, Session 2Python + Machine Learning Course, Session 2
Python + Machine Learning Course, Session 2
 
Python + Machine Learning Course, Session 1
Python + Machine Learning Course, Session 1Python + Machine Learning Course, Session 1
Python + Machine Learning Course, Session 1
 
.NET Core, ASP.NET Core Course, Session 5
.NET Core, ASP.NET Core Course, Session 5.NET Core, ASP.NET Core Course, Session 5
.NET Core, ASP.NET Core Course, Session 5
 
.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4.NET Core, ASP.NET Core Course, Session 4
.NET Core, ASP.NET Core Course, Session 4
 
.NET Core, ASP.NET Core Course, Session 1
.NET Core, ASP.NET Core Course, Session 1.NET Core, ASP.NET Core Course, Session 1
.NET Core, ASP.NET Core Course, Session 1
 
A comparative study of process templates in team
A comparative study of process templates in teamA comparative study of process templates in team
A comparative study of process templates in team
 
SQL server 2016 New Features
SQL server 2016 New FeaturesSQL server 2016 New Features
SQL server 2016 New Features
 

Recently uploaded

Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
Paul Brebner
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
Jhone kinadey
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
Severalnines
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
kgyxske
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
widenerjobeyrl638
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
kalichargn70th171
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio, Inc.
 
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in NashikUpturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
OnePlan Solutions
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
vaishalijagtap12
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
The Third Creative Media
 

Recently uploaded (20)

Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
 
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in NashikUpturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in Nashik
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
 

.NET Core, ASP.NET Core Course, Session 11

  • 1. .NET Core + ASP.NET Core Training Course Session 11
  • 2. .NET Core What we learned? Session 6 ~ 10 Overview • ASP.NET Core Basics • Middleware in ASP.NET core • Controllers • Action Filters • Routing • Model Binding • Model Validation
  • 3. .NET Core What we’ll learn today? Session 11 Agenda • Views
  • 4. .NET Core Views Views ASP.NET MVC Core controllers can return formatted results using views. The view encapsulates the presentation details of the user’s interaction with the app. Views are HTML templates with embedded code that generate content to send to the client. Views use Razor syntax, which allows code to interact with HTML with minimal code or ceremony.
  • 5. .NET Core Views Views views are .cshtml files stored by default in a Views folder within the application. Typically, each controller will have its own folder, in which are views for specific controller actions. Views provide separation of concerns within an MVC app, encapsulating user interface level markup separately from business logic. ASP.NET MVC views use Razor syntax to make switching between HTML markup and server side logic painless.
  • 6. .NET Core Creating a View Views - Creating Views that are specific to a controller are created in the Views/[ControllerName] folder. Views that are shared among controllers are placed in the /Views/Shared folder.
  • 7. .NET Core Creating a View Views - Creating Razor code is denoted by the @ symbol. C# statements are run within Razor code blocks set off by curly braces ({ }) How do Controllers Specify Views? Views are typically returned from actions as a ViewResult. Your action method can create and return a ViewResult directly, but more commonly if your controller inherits from Controller, you’ll simply use the View helper method. You can optionally specify a view to return, as well as a model object to pass to the view.
  • 8. .NET Core View Discovery Views - Discovery When an action returns a view, a process called view discovery takes place. This process determines which view file will be used. Unless a specific view file is specified, the runtime looks for a controller-specific view first, then looks for matching view name in the Shared folder. view discovery searches for a matching view file in: 1. Views/<ControllerName>/<ViewName>.cshtml 2. Views/Shared/<ViewName>.cshtml
  • 9. .NET Core View Discovery Views - Discovery A view file path can be provided, instead of a view name. In this case, the .cshtml extension must be specified as part of the file path. The path should be relative to the application root (and can optionally start with “/” or “~/”). For example: return View("Views/Home/About.cshtml"); customize the default convention regarding where views are located within the app by using a custom IViewLocationExpander.
  • 10. .NET Core Razor View Names Views View names may be case sensitive depending on the underlying file system. For compatibility across operating systems, always match case between controller and action names and associated view folders and filenames.
  • 11. .NET Core Passing Data to Views Views You can pass data to views using several mechanisms. The most robust approach is to specify a model type in the view (commonly referred to as a viewmodel, to distinguish it from business domain model types), and then pass an instance of this type to the view from the action. It’s recommend to use a model or view model to pass data to a view. This allows the view to take advantage of strong type checking. You can specify a model for a view using the @model directive
  • 12. .NET Core Passing Data to Views Views Once a model has been specified for a view, the instance sent to the view can be accessed in a strongly-typed manner using @Model as shown above.
  • 13. .NET Core Passing Data to Views Views To provide an instance of the model type to the view, the controller passes it as a parameter There are no restrictions on the types that can be provided to a view as a model. We recommend passing Plain Old CLR Object (POCO) view models with little or no behavior, so that business logic can be encapsulated elsewhere in the app.
  • 14. .NET Core Loosely Typed Data Views In addition to strongly typed views, all views have access to a loosely typed collection of data. This same collection can be referenced through either the ViewData or ViewBag properties on controllers and views. The ViewBag property is a wrapper around ViewData that provides a dynamic view over that collection. It is not a separate collection.
  • 15. .NET Core Loosely Typed Data Views ViewData is a dictionary object accessed through string keys. You can store and retrieve objects in it, and you’ll need to cast them to a specific type when you extract them. You 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.
  • 17. .NET Core Loosely Typed Data Views 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. The same example as above, using ViewBag instead of a strongly typed address instance in the view:
  • 18. .NET Core Dynamic Views Views Views that do not declare a model type but have a model instance passed to them can reference this instance dynamically. For example, if an instance of Address is passed to a view that doesn’t declare an @model, the view would still be able to refer to the instance’s properties dynamically. This feature can offer some flexibility, but does not offer any compilation protection or IntelliSense. If the property doesn’t exist, the page will fail at runtime.
  • 19. .NET Core Partial Views Views - Partial Views ASP.NET Core MVC supports partial views, which are useful when you have reusable parts of web pages you want to share between different views. A partial view is a view that is rendered within another view. The HTML output generated by executing the partial view is rendered into the calling (or parent) view. Like views, partial views use the .cshtml file extension.
  • 20. .NET Core When Should I Use Partial Views? Views - Partial Views Partial views are an effective way of breaking up large views into smaller components. They can reduce duplication of view content and allow view elements to be reused. Common layout elements should be specified in _Layout.cshtml. Non-layout reusable content can be encapsulated into partial views.
  • 21. .NET Core When Should I Use Partial Views? Views - Partial Views If you have a complex page made up of several logical pieces, it can be helpful to work with each piece as its own partial view. Each piece of the page can be viewed in isolation from the rest of the page, and the view for the page itself becomes much simpler since it only contains the overall page structure and calls to render the partial views.
  • 22. .NET Core Declaring Partial Views Views - Partial Views You can have a view that is returned directly from a controller’s ViewResult, and the same view can be used as a partial view. The main difference between how a view and a partial view are rendered is that partial views do not run _ViewStart.cshtml (while views do - learn more about _ViewStart.cshtml in Layout).
  • 23. .NET Core Referencing a Partial View Views - Partial Views From within a view page, there are several ways in which you can render a partial view. The simplest is to use Html.Partial, which returns an IHtmlString and can be referenced by prefixing the call with @: @Html.Partial("AuthorPartial") The PartialAsync method is available for partial views containing asynchronous code (although code in views is generally discouraged): @await Html.PartialAsync("AuthorPartial")
  • 24. .NET Core Referencing a Partial View Views - Partial Views You can render a partial view with RenderPartial. This method doesn’t return a result; it streams the rendered output directly to the response. Because it doesn’t return a result, it must be called within a Razor code block (you can also call RenderPartialAsync if necessary): @{ Html.RenderPartial("AuthorPartial"); }
  • 25. .NET Core Partial View Discovery Views - Partial Views
  • 26. .NET Core Referencing a Partial View Views - Partial Views If desired, you can have different partial views with the same name in different view folders. When referencing the views by name (without file extension), views in each folder will use the partial view in the same folder with them. You can also specify a default partial view to use, placing it in the Shared folder. This view will be used by any views that don’t have their own copy of the partial view in their folder. In this way, you can have a default partial view (in Shared), which can be overridden by a partial view with the same name in the same folder as the parent view.
  • 27. .NET Core Referencing a Partial View Views - Partial Views Partial views can be chained. That is, a partial view can call another partial view (as long as you don’t create a loop). Within each view or partial view, relative paths are always relative to that view, not the root or parent view.
  • 28. .NET Core Accessing Data From Partial Views Views - Partial Views When a partial view is instantiated, it gets a copy of the parent view’s ViewData dictionary. Updates made to the data within the partial view are not persisted to the parent view. ViewData changed in a partial view is lost when the partial view returns. You can pass an instance of ViewDataDictionary to the partial view: @Html.Partial("PartialName", customViewData)
  • 29. .NET Core Accessing Data From Partial Views Views - Partial Views You can also pass a model into a partial view. This can be the page’s view model, or some portion of it, or a custom object. Simply pass in the model as the second parameter when calling Partial/PartialAsync or RenderPartial/RenderPartialAsync: @Html.Partial("PartialName", viewModel) You can pass an instance of ViewDataDictionary and a view model to a partial view: @Html.Partial("PartialName", viewModel, customViewData)
  • 30. .NET Core What is a Layout? Layout Most web apps have a common layout that provides the user with a consistent experience as they navigate from page to page. The layout typically includes common user interface elements such as the app header, navigation or menu elements, and footer.
  • 31. .NET Core What is a Layout? Layout By convention, the default layout for an ASP.NET app is named _Layout.cshtml. Razor views have a Layout property. Individual views specify a layout by setting this property: @{ Layout = "_Layout"; }
  • 32. .NET Core What is a Layout? Layout The layout specified can use a full path (example: /Views/Shared/_Layout.cshtml) or a partial name (example: _Layout). When a partial name is provided, the Razor view engine will search for the layout file using its standard discovery process. The controller-associated folder is searched first, followed by the Shared folder. This discovery process is identical to the one used to discover partial views.
  • 33. .NET Core Using Layout Layout By default, every layout must call RenderBody. Wherever the call to RenderBody is placed, the contents of the view will be rendered. A layout can optionally reference one or more sections, by calling RenderSection. Sections provide a way to organize where certain page elements should be placed. Each call to RenderSection can specify whether that section is required or optional. If a required section is not found, an exception will be thrown.
  • 34. .NET Core Using Layout Layout An example @section definition in a view: @section Scripts { <script type="text/javascript" src="/scripts/main.js"></script> } Sections defined in a view are available only in its immediate layout page. They cannot be referenced from partials, view components, or other parts of the view system.
  • 35. .NET Core Using Layout - Ignoring sections Layout By default, the body and all sections in a content page must all be rendered by the layout page. The Razor view engine enforces this by tracking whether the body and each section have been rendered. To instruct the view engine to ignore the body or sections, call the IgnoreBody and IgnoreSection methods. The body and every section in a Razor page must be either rendered or ignored.
  • 36. .NET Core Using Layout - Importing Shared Directives Layout Views can use Razor directives to do many things, such as importing namespaces or performing dependency injection. Directives shared by many views may be specified in a common _ViewImports.cshtml file. The _ViewImports file supports the following directives: • @addTagHelper • @removeTagHelper • @tagHelperPrefix • @using • @model • @inherits • @inject
  • 37. .NET Core Using Layout - _ViewImports.cshtml Layout A sample _ViewImports.cshtml file: @using WebApplication1 @using WebApplication1.Models @using WebApplication1.Models.AccountViewModels @using WebApplication1.Models.ManageViewModels @using Microsoft.AspNetCore.Identity @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
  • 38. .NET Core Using Layout - _ViewImports.cshtml Layout The _ViewImports.cshtml file for an ASP.NET Core MVC app is typically placed in the Views folder. A _ViewImports.cshtml file can be placed within any folder, in which case it will only be applied to views within that folder and its subfolders. _ViewImports files are processed starting at the root level, and then for each folder leading up to the location of the view itself, so settings specified at the root level may be overridden at the folder level.
  • 39. .NET Core Using Layout - _ViewImports.cshtml Layout For example, if a root level _ViewImports.cshtml file specifies @model and @addTagHelper, and another _ViewImports.cshtml file in the controller- associated folder of the view specifies a different @model and adds another @addTagHelper, the view will have access to both tag helpers and will use the latter @model.
  • 40. .NET Core Using Layout - _ViewImports.cshtml Layout If multiple _ViewImports.cshtml files are run for a view, combined behavior of the directives included in the ViewImports.cshtml files will be as follows: @addTagHelper, @removeTagHelper: all run, in order @tagHelperPrefix: the closest one to the view overrides any others @model: the closest one to the view overrides any others @inherits: the closest one to the view overrides any others @using: all are included; duplicates are ignored @inject: for each property, the closest one to the view overrides any others with the same property name
  • 41. .NET Core Running Code Before Each View Layout If you have code you need to run before every view, this should be placed in the _ViewStart.cshtml file. By convention, the _ViewStart.cshtml file is located in the Views folder. The statements listed in _ViewStart.cshtml are run before every full view (not layouts, and not partial views). Like ViewImports.cshtml, _ViewStart.cshtml is hierarchical.
  • 42. .NET Core View Components View Components New to ASP.NET Core MVC, view components are similar to partial views, but they are much more powerful. View components don’t use model binding, and only depend on the data you provide when calling into it. A view component: • Renders a chunk rather than a whole response • Includes the same separation-of-concerns and testability benefits found between a controller and view • Can have parameters and business logic • Is typically invoked from a layout page
  • 43. .NET Core View Components View Components View Components are intended anywhere you have reusable rendering logic that is too complex for a partial view, such as: • Dynamic navigation menus • Tag cloud (where it queries the database) • Login panel • Shopping cart • Recently published articles • Sidebar content on a typical blog • A login panel that would be rendered on every page and show either the links to log out or log in, depending on the log in state of the user
  • 44. .NET Core View Components View Components A view component consists of two parts, the class (typically derived from ViewComponent) and the result it returns (typically a view). Like controllers, a view component can be a POCO, but most developers will want to take advantage of the methods and properties available by deriving from ViewComponent.
  • 45. .NET Core Creating a view component View Components A view component class can be created by any of the following: • Deriving from ViewComponent • Decorating a class with the [ViewComponent] attribute, or deriving from a class with the [ViewComponent] attribute • Creating a class where the name ends with the suffix ViewComponent Like controllers, view components must be public, non-nested, and non-abstract classes. The view component name is the class name with the “ViewComponent” suffix removed. It can also be explicitly specified using the ViewComponentAttribute.Name property.
  • 46. .NET Core Creating a view component View Components A view component class: • Fully supports constructor dependency injection • Does not take part in the controller lifecycle, which means you can’t use filters in a view component
  • 47. .NET Core View component methods View Components A view component defines its logic in an InvokeAsync method that returns an IViewComponentResult. Parameters come directly from invocation of the view component, not from model binding. A view component never directly handles a request. Typically a view component initializes a model and passes it to a view by calling the View method.
  • 48. .NET Core View component methods View Components • Define an InvokeAsync` method that returns an IViewComponentResult • Typically initializes a model and passes it to a view by calling the ViewComponent View method • Parameters come from the calling method, not HTTP, there is no model binding • Are not reachable directly as an HTTP endpoint, they are invoked from your code (usually in a view). A view component never handles a request • Are overloaded on the signature rather than any details from the current HTTP request
  • 49. .NET Core View components - View search path View Components The runtime searches for the view in the following paths: • Views/<controller_name>/Components/<view_component_name>/<view_na me> • Views/Shared/Components/<view_component_name>/<view_name> The default view name for a view component is Default, which means your view file will typically be named Default.cshtml. You can specify a different view name when creating the view component result or when calling the View method.
  • 50. .NET Core View components - View search path View Components We recommend you name the view file Default.cshtml and use the Views/Shared/Components/<view_component_name>/<view_name> path.
  • 51. .NET Core Invoking a view component View Components To use the view component, call @Component.InvokeAsync("Name of view component", <anonymous type containing parameters>) from a view. The parameters will be passed to the InvokeAsync method. In the following, the InvokeAsync method is called with two parameters: @await Component.InvokeAsync("PriorityList", new { maxPriority = 2, isDone = false })
  • 52. .NET Core Invoking a view component directly from a controller View Components View components are typically invoked from a view, but you can invoke them directly from a controller method. While view components do not define endpoints like controllers, you can easily implement a controller action that returns the content of a ViewComponentResult. In this example, the view component is called directly from the controller: public IActionResult IndexVC() { return ViewComponent("PriorityList", new { maxPriority = 3, isDone = false }); }
  • 53. .NET Core Creating a simple view component demo View Components
  • 54. .NET Core Creating a simple view component demo View Components Notes on the code: • View component classes can be contained in any folder in the project. • Because the class name PriorityListViewComponent ends with the suffix ViewComponent, the runtime will use the string “PriorityList” when referencing the class component from a view. I’ll explain that in more detail later.
  • 55. .NET Core Creating a simple view component demo View Components Notes on the code: • The [ViewComponent] attribute can change the name used to reference a view component. For example, we could have named the class XYZ, and applied the ViewComponent attribute: [ViewComponent(Name = "PriorityList")] public class XYZ : ViewComponent
  • 56. .NET Core Injecting Services Into Views Injecting Services Into Views ASP.NET Core supports dependency injection into views. This can be useful for view-specific services, such as localization or data required only for populating view elements. You can inject a service into a view using the @inject directive. You can think of @inject as adding a property to your view, and populating the property using DI.
  • 57. .NET Core Injecting Services Into Views Injecting Services Into Views The syntax for @inject: @inject <type> <name>
  • 58. .NET Core Injecting Services Into Views Injecting Services Into Views The summary is populated from the injected StatisticsService. This service is registered for dependency injection in ConfigureServices in Startup.cs:
  • 59. .NET Core Injecting Services Into Views Injecting Services Into Views View injection can be useful to populate options in UI elements, such as dropdown lists. Consider a user profile form that includes options for specifying gender, state, and other preferences. Rendering such a form using a standard MVC approach would require the controller to request data access services for each of these sets of options, and then populate a model or ViewBag with each set of options to be bound.
  • 60. .NET Core Injecting Services Into Views Injecting Services Into Views An alternative approach injects services directly into the view to obtain the options. This minimizes the amount of code required by the controller, moving this view element construction logic into the view itself.
  • 61. .NET Core Injecting Services Into Views Injecting Services Into Views
  • 62. .NET Core Injecting Services Into Views Injecting Services Into Views Overriding Services In addition to injecting new services, this technique can also be used to override previously injected services on a page. The figure below shows all of the fields available on the page used in the first example:
  • 63. .NET Core Injecting Services Into Views Injecting Services Into Views Overriding Services As you can see, the default fields include Html, Component, and Url (as well as the StatsService that we injected). If for instance you wanted to replace the default HTML Helpers with your own, you could easily do so using @inject: