title
stringlengths
3
46
content
stringlengths
0
1.6k
17:490
var myVar = 5;
17:491
...
17:492
<div>
17:493
<!-- here you are in HTML mode again -->
17:494
...
17:495
</div>
17:496
//after the HTML block you are still in C# mode
17:497
var x = `my string`;
17:498
}
17:499
17:500
The preceding example shows that it is enough to write an HTML tag to create an HTML area inside the C# area and so on recursively. As soon as the HTML tag closes, you are in C# mode again.
17:501
If we need to create an HTML area but don’t want to enclose it in an HTML tag, we can use the fake <text> tag provided by Razor syntax:
17:502
<text>
17:503
<!-- here you entered HTML mode without adding an enclosing
17:505
...
17:506
</text>
17:507
17:508
C# code produces no HTML, while HTML code is added to the response in the same order in which it appears. You can add text computed with C# code while in HTML mode by prefixing any C# expression with @. If the expression is complex, in that it is composed of a chain of properties and method calls, it must be enclosed by parentheses. The following code shows some examples:
17:509
<span>Current date is: </span>
17:510
<span>@DateTime.Today.ToString(`d`)</span>
17:511
...
17:512
<p>
17:513
User name is: @($`{myName} {mySurname}`)
17:514
</p>
17:515
...
17:516
<input type=`submit` value=`@myUserMessage` />
17:517
17:518
The @ itself can be escaped by entering it twice – @@.
17:519
Types are converted into strings using the current culture settings (see the Understanding the connection between ASP.NET Core MVC and design principles section for details on how to set the culture of each request). Moreover, strings are automatically HTML-encoded to avoid the < and > symbols, which might interfere with the view HTML.
17:520
HTML encoding can be prevented with the @HTML.Raw function, as shown here:
17:521
@HTML.Raw(myDynamicHtml)
17:522
17:523
In an HTML area, alternative HTML can be selected with the @if Razor statement:
17:524
@if(myUser.IsRegistered)
17:525
{
17:526
//this is a C# code area
17:527
var x=5;
17:528
...
17:529
<p>
17:530
<!-- This is an HTML area -->
17:531
</p>
17:532
//this is a C# code area again
17:533
}
17:534
else if(myUser.IsNew)
17:535
{
17:536
...
17:537
}
17:538
else
17:539
{
17:540
..
17:541
}
17:542
17:543
As shown in the preceding code, the beginning of each block of a Razor control flow statement is in C# mode and remains so until the first HTML open tag is encountered, and then, HTML mode starts. C# mode is resumed after the corresponding HTML close tag.
17:544
An HTML template can be instantiated several times with the for, foreach, while, and do Razor statements, as shown in the following examples:
17:545
@for(int i=0; i< 10; i++)
17:546
{
17:547
}
17:548
@foreach(var x in myIEnumerable)
17:549
{
17:550
}
17:551
@while(true)
17:552
{
17:553
17:554
}
17:555
@do
17:556
{
17:557
17:558
}
17:559
while(true)
17:560
17:561
Razor views can contain comments that do not generate any code. Any text included within @*...*@ is considered a comment and removed when the page is compiled. With a good understanding of controllers and their operational mechanics, let’s now turn to how ASP.NET Core MVC generates HTML responses using Razor views.
17:562
Understanding Razor view properties
17:563
Some standard variables are predefined in each view. The most important variable is Model, which contains the ViewModel that was passed to the view. For instance, if we pass a Person model to a view, then <span>@Model.Name</span> displays the name of the Person model that was passed to the view.
17:564
The ViewData variable contains IDictionary<string, object>, which is shared with the controller that invoked the view; that is, all controllers also have a ViewData property containing IDictionary<string, object>, and every entry that is set in the controller is also available in the ViewData variable of the invoked view. ViewData is an alternative to the ViewModel for a controller, allowing the passing of information to its invoked view. It is worth mentioning that the ViewData dictionary can also be accessed as a dynamic object through the ViewBag property. This means that dynamic ViewBag properties are mapped to ViewData string indices and that their values are mapped to the ViewData entries corresponding to those indices. Using ViewData or ViewBag is just a matter of preference; neither one has an advantage over the other.
17:565
Often, ViewData is used to store collateral data such as the value-string pairs used to populate an HTML Select. For instance, let’s suppose the ViewModel model contains TownId and TownName properties that the user can change, by selecting a different town from an HTML Select. In this case, the action method might fill the `AllTowns` entry of ViewData with all possible town ID and town name pairs:
17:566
ViewData[=[`AllTowns`]= await townsRepo.GetAll();
17:567
...
17:568
return View(new AddressViewModel{...});
17:569
17:570
Both controllers and Views also contain a TempData dictionary, whose entries are remembered between two successive requests. Due to a lack of space, we can’t discuss its properties and its usage, but the interested among you can refer to the official Microsoft documentation:
17:571
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-8.0#tempdata
17:572
The User view variable contains the currently logged-in user, that is, the same instance contained in the current request’s Http.Context.User property. The Url variable contains an instance of the IUrlHelper interface, whose methods are utilities for computing the URLs of application pages. For instance, Url.Action(`action`, `controller`, new {par1=valueOfPar1,...}) computes the URL that causes the action method, action, of controller to be invoked, with all the parameters specified in the anonymous object passed as its parameters.
17:573
The Context variable contains the whole request’s HttpContext. The ViewContext variable contains data about the context of the view invocation, including metadata about the action method that invoked the view.
17:574
The next topic describes how Razor views enhance HTML tag syntax.
17:575
Using Razor tag helpers
17:576
Tag helpers in ASP.NET Core MVC are powerful tools for enhancing HTML tags with additional functionalities. More specifically, a tag helper either enhances existing HTML tags with new tag attributes or defines completely new tags.
17:577
While Razor views are compiled, any tag is matched against existing tag helpers. When a match is found, the source tag is replaced with HTML created by the tag helpers. Several tag helpers may be defined for the same tag. They are all executed in an order that can be configured with a priority attribute associated with each tag helper.
17:578
All tag helpers defined for the same tag may cooperate while each tag instance is being processed. This is because they are passed a shared data structure where each of them may apply a contribution. Usually, the final tag helper that is invoked processes this shared data structure to produce the output HTML.
17:579
Tag helpers are classes that inherit from the TagHelper class. This topic doesn’t discuss how to create new tag helpers, but it does introduce the main predefined tag helpers that come with ASP.NET Core MVC. A complete guide on how to define tag helpers is available in the official documentation, which is referenced in the Further reading section.
17:580
To use a tag helper, you must declare the .dll file that contains the tag helper with a declaration like the following:
17:581
@addTagHelper *, Dll.Complete.Name
17:582
17:583
If you would like to use just one of the tag helpers defined in the .dll file, you must replace * with the tag name.
17:584
The preceding declaration can be placed either in each view that uses the tag helpers defined in the library or, ultimately, in the _ViewImports.cshtml file in the root of the Views folder. By default, _ViewImports.cshtml adds all predefined ASP.NET Core MVC tag helpers with the following declaration:
17:585
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
17:586
17:587
The anchor tag is enhanced with attributes that automatically compute the URL and invoke a specific action method with given parameters, as shown here:
17:588
<a asp-controller=`{controller name}`
17:589
asp-action=`{action method name}`
17:590
asp-route-{action method parameter1}=`value1`