Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
299 views

CSharp-ASP-NET-Core-Razor-Views-and-Layouts

Soft Uni lecture on c# razor views and layouts

Uploaded by

Michael-S
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
299 views

CSharp-ASP-NET-Core-Razor-Views-and-Layouts

Soft Uni lecture on c# razor views and layouts

Uploaded by

Michael-S
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Razor Views

Views, Razor Syntax, Layout, Tag Helpers, View Components

SoftUni Team
Technical Trainers
Software University
https://softuni.bg
Table of Contents

 View Engine Essentials


 Razor Syntax
 Dependency Injection
 Layout and Special View Files
 _Layout, _ViewStart, _ViewImports and Sections
 HTML Helpers & Tag Helpers
 Partial Views & View Components

2
Have a Question?

sli.do
#csharp-web
3
View Engine Essentials
View Engine Essentials
 Views in ASP.NET Core MVC use the Razor View Engine to embed
.NET Code in HTML Markup.
 Usually, they contain minimal logic, related only to presenting data
 Data can be passed to a View by using the ViewData, ViewBag or
through a ViewModel (Strongly-Typed View).

5
Passing Data to a View
 With ViewBag (dynamic type):
 Action: ViewBag.Message = "Hello World!";
 View: @ViewBag.Message
 With ViewData (dictionary)
 Action: ViewData["message"] = "Hello World!";
 View: @ViewData["message"]
 With Strongly-typed views:
 Action: return View(model);
 View: @model ModelDataType and then @Model.Message
6
Returning Views
 The Base Controller class provides a lot of functionality
 View() method – One of the most frequently used Controller class members
public class HomeController : Controller public IActionResult Index()
{ {
public IActionResult Index() return
{
this.View("~/Views/Other/Index.cshtml");
return this.View();
} }
}

7
How It Works?

View ViewModel Controller

Generated
Output
8
Razor Syntax
Razor Syntax
 @ – For values (HTML encoded)
<p>
Current time is: @DateTime.Now!!!
Not HTML encoded value: @Html.Raw(someVar)
</p>

 @{ … } – For code blocks (keep the view simple!)


@{
var productName = "Energy drink";
if (Model != null) { productName = Model.ProductName; }
else if (ViewBag.ProductName != null) { productName = ViewBag.ProductName; }
}
<p>Product "@productName" has been added in your shopping cart</p>

10
Razor Syntax (2)
 If, else, for, foreach, etc. C# statements
 HTML markup lines can be included at any part
 @: – For plain text line to be rendered
<div class="products-list">
@if (Model.Products.Count() == 0) { <p>Sorry, no products found!</p> }
else
{
@:List of the products found:
foreach(var product in Model.Products)
{
<b>@product.Name, </b>
}
}
</div>
11
Razor Syntax (3)
 Comments
@*
A Razor Comment
*@
@{
// A C# comment
/* A Multi
line C# comment
*/
}
<!-- HTML Comment -->

 What about "@" and emails?


<p>
This is the sign that separates email names from domains: @@<br />
And this is how smart Razor is: spam_me@gmail.com
</p>
12
Razor Syntax (4)
 @(…) – Explicit code expression
<p>
Current rating(0-10): @Model.Rating / 10.0 @* 6 / 10.0 *@
Current rating(0-1): @(Model.Rating / 10.0) @* 0.6 *@
spam_me@Model.Rating @* spam_me@Model.Rating *@
spam_me@(Model.Rating) @* spam_me6 *@
</p>

 @using – for including namespace into view


 @model – for defining the model for the view
@using MyFirstMvcApplication.Models;
@model UserModel
<p>@Model.Username</p>
13
Views – Dependency Injection
 ASP.NET Core supports dependency injection into views.
 You can inject a Service into a View by using @inject

14
Layout and Special View Files
Layout
 Define a common site template (~/Views/Shared/_Layout.cshtml)
 Razor View engine renders content inside-out
 First the View is rendered, and after that – the Layout
 @RenderBody() –
indicate where we want
the views based on this
layout to "fill in" their
core content at that
location in the HTML
16
_ViewStart.cshtml
 Views don't need to specify layout since their default layout is
set in their _ViewStart file:
 ~/Views/_ViewStart.cshtml (code for all views)
 Each view can specify custom layout pages
@{
Layout = "~/Views/Shared/_UncommonLayout.cshtml";
}

 Views without layout:


@{
Layout = null;
}
17
_ViewImports.cshtml
 If a directive or a dependency is shared between many Views it
can be specified globally in the ViewImports:
 ~/Views/_ViewImports.cshtml (code for all views)
@using WebApplication1
@using WebApplication1.Models
@using WebApplication1.Models.AccountViewModels
@using WebApplication1.Models.ManageViewModels
@using Microsoft.AspNetCore.Identity
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

 This file does not support other Razor features


18
Sections
 You can have one or more "sections" (optional)
 They are defined in the views:

 Can be rendered anywhere in the layout page using the method


RenderSection()
 @RenderSection(string name, bool required)
 If the section is required and not defined, an exception will be
thrown (IsSectionDefined())
19
HTML Helpers and Tag Helpers
HTML Helpers
 Each view inherits RazorPage
 RazorPage has a property named Html
 The Html Property has methods that
return string can be used to:
HTML Helpers
 Create inputs @Html.ActionLink @Html.TextBox
 Create links @Html.BeginForm @Html.TextArea
@Html.CheckBox @Html.Password
 Create forms
@Html.Display @Html.Hidden
 Avoid using HTML Helpers @Html.Editor @Html.Label
@Html.DropDownList @Html.Action
 Use Tag Helpers instead
21
Tag Helpers
 Tag Helpers enable the participation of Server-side code in the
HTML element creation and rendering, in Razor views
 There are built-in Tag Helpers for many common tasks
 Forms, Links, Assets etc.
 There are custom Tag Helpers in GitHub repos and NuGet
 Tag Helpers provide
 An HTML-friendly development experience
 A rich IntelliSense environment for creating Razor markup
 A more productive, reliable and maintainable code 22
Tag Helpers vs HTML Helpers
 Tag Helpers attach to HTML  HTML Helpers are invoked as
elements in Razor Views methods which generate content
 Tag Helpers reduce the explicit  HTML Helpers tend to include a
transitions between HTML & C# lot of C# code in the markup
 Tag Helpers make the Razor  HTML Helpers use complex and
markup quite clean and the very C#-specific Razor syntax in
views – quite simple some cases

23
Tag Helpers vs HTML Helpers

24
Creating Your Own Tag Helper
[HtmlTargetElement("h1")]
public class HelloTagHelper : TagHelper
{
private const string MessageFormat = "Hello, {0}";
public string TargetName { get; set; }

public override void Process(TagHelperContext context, TagHelperOutput output)


{
string formattedMessage = string.Format(MessageFormat, this.TargetName);
output.Content.SetContent(formattedMessage);
}
}

@using WebApplication;
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelper
@addTagHelper WebApplication.TagHelpersHelloTagHelper, WebApplication

<div class="tag-helper-content">
<h1 target-name="John"></h1>
</div>
25
Partial Views & View Components
Partial Views
 Partial Views render portions of a page
 Break up large markup files into smaller components
 Reduce the duplication of common view code
 Razor partial views are normal views (.cshtml files)
 Usually placed in /Shared/ or in the same directory where used
 Can be referenced with HTML helper or Tag Helper
 Html helpers: Partial, PartialAsync, RenderPartial, etc.
 Tag helper: <partial name="" model="" view-data="" for="" />
27
Use of Partial Views
 HTML Helper for Partial Views
@using WebApplication.Models;
@model ProductsListViewModel

@foreach (var product in Model.Products)


{
@await Html.PartialAsync("_ProductPartial", product);
}

 Tag Helper for Partial Views


@foreach (var product in Model.Products)
{
<partial name="_ProductPartial" model="product" />
}
28
View Components
 View Components are similar to Partial Views but much more powerful
 No model binding
 Depend only on the data provided to it
 View Components:
 Render a chunk rather than a whole response (as in Html.Action())
 Can have parameters and business logic
 Is typically invoked from a Layout page
 Includes the same S-o-C and testability benefits between
controller / view
29
View Components
 View components are intended anywhere you have reusable rendering
logic that's too complex for a partial view
 Dynamic navigation menus
 Login panels
 Shopping carts
 Sidebar content
 Recently published
articles
 Tag cloud
30
View Components
 View Components consist of 2 parts:
 A class – typically derived from ViewComponent
 A result – typically a View
 View Components
 Define their logic in a method called InvokeAsync()
 Never directly handle a Request
 Typically initialize a Model which is passed to the View

31
Defining Your Own ViewComponent
[ViewComponent(Name = "HelloWorld")]
public class HelloWorldViewComponent : ViewComponent
{
private readonly DataService dataService;
public HelloWorldViewComponent(DataService dataService)
{
this.dataService = dataService;
}

public async Task<IViewComponentResult> InvokeAsync(string name)


{
string helloMessage =
await this.dataService.GetHelloAsync();

this.ViewData["Message"] = helloMessage;
this.ViewData["Name"] = name;

return View();
}
}
32
Defining Your Own ViewComponent
@* In Default.cshtml *@
<h1>@ViewData["Message"]!!! I am @ViewData["Name"]</h1>

<div class="view-component-content">
@await Component.InvokeAsync("HelloWorld", new { name = "David" });
<vc:HelloWorld name="John"></vc:HelloWorld>
</div>

33
Summary

  Razor
… View Engine Essentials
 Razor Syntax
 …
 Layout and Special Views
 …
 Sections
 Tag Helpers & HTML Helpers
 Partial Views & View Components

34
Questions?

© SoftUni – https://softuni.org. Copyrighted document. Unauthorized copy, reproduction or use is not permitted.
Trainings @ Software University (SoftUni)
 Software University – High-Quality Education,
Profession and Job for Software Developers
 softuni.bg, softuni.org
 Software University Foundation
 softuni.foundation
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg
 3
License

 This course (slides, examples, demos, exercises, homework,


documents, videos and other assets) is copyrighted content
 Unauthorized copy, reproduction or use is illegal
 © SoftUni – https://softuni.org
 © Software University – https://softuni.bg

37

You might also like