title
stringlengths
3
46
content
stringlengths
0
1.6k
17:691
Figure 17.7: Using layout pages
17:692
Each view can specify the view to be used as its layout page with the following code:
17:693
@{
17:694
Layout = `_MyLayout`;
17:695
}
17:696
17:697
If no layout page is specified, a default layout page, defined in a _ViewStart.cshtml file located in the Views folder, is used. The default content of _ViewStart.cshtml is as follows:
17:698
@{
17:699
Layout = `_Layout`;
17:700
}
17:701
17:702
Therefore, the default layout page in the files scaffolded by Visual Studio is _Layout.cshtml, which is contained in the Shared folder.
17:703
The layout page contains the HTML that’s shared with all of its children pages, the HTML page headers, and the page references to CSS and JavaScript files. The HTML produced by each view is placed inside its layout page, where the layout page calls the @RenderBody() method, as shown in the following example:
17:704
...
17:705
<main role=`main` class=`pb-3`>
17:706
...
17:707
@RenderBody()
17:708
...
17:709
</main>
17:710
...
17:711
17:712
ViewData of each View is copied into ViewData of its layout page, so ViewData can be used to pass information to the view layout page. Typically, it is used to pass the view title to the layout page, which then uses it to compose the page’s title header, as shown here:
17:713
@*In the view *@
17:714
@{
17:715
ViewData[`Title`] = `Home Page`;
17:716
}
17:717
@*In the layout view*@
17:718
<head>
17:719
<meta charset=`utf-8` />
17:720
...
17:721
<title>@ViewData[`Title`] - My web application</title>
17:722
...
17:723
17:724
While the main content produced by each view is placed in a single area of its layout page, each layout page can also define several sections placed in different areas, where each view can place further secondary content.
17:725
For instance, suppose a layout page defines a Scripts section, as shown here:
17:726
...
17:727
<script src=`~/js/site.js` asp-append-version=`true`></script>
17:728
@RenderSection(`Scripts`, required: false)
17:729
...
17:730
17:731
Then, the view can use the previously defined section to pass some view-specific JavaScript references, as shown here:
17:732
.....
17:733
@section scripts{
17:734
<script src=`~/js/pages/pageSpecificJavaScript.min.js`></script>
17:735
}
17:736
.....
17:737
17:738
If an action method is expected to return HTML to an AJAX call, it must produce an HTML fragment instead of a whole HTML page. Therefore, in this case, no layout page must be used. This is achieved by calling the PartialView method instead of the View method in the controller action method. PartialView and View have exactly the same overloads and parameters.
17:739
Another way to reuse view code is to factor out a view fragment that’s common to several views into another view that is called by all previous views. A view can call another view with the partial tag, as shown here:
17:740
<partial name=`_viewname` for=`ModelProperty.NestedProperty`/>
17:741
17:742
The preceding code invokes _viewname and passes it to the object contained in Model.ModelProperty.NestedProperty as its ViewModel. When a view is invoked by the partial tag, no layout page is used, since the called view is expected to return an HTML fragment.
17:743
The ViewData.TemplateInfo.HtmlFieldPrefix property of the called view is set to the ModelProperty.NestedProperty string. This way, possible input fields rendered in _viewname.cshtml will have the same name as if they had been rendered directly by the calling view.
17:744
Instead of specifying the ViewModel of _viewname through a property of the caller view (ViewModel), you can also directly pass an object that is contained in a variable or returned by a C# expression by replacing for with model, as shown in this example:
17:745
<partial name=`_viewname` model=`new MyModel{...})` />
17:746
17:747
In this case, the ViewData.TemplateInfo.HtmlFieldPrefix property of the called view keeps its default value, that is, the empty string.
17:748
A view can also call something more complex than another view, that is, another controller method that, in turn, renders a view. Controllers that are designed to be invoked by views are called view components. The following code is an example of component invocation:
17:749
<vc:[view-component-name] par1=`par1 value` par2=`parameter2 value`> </vc:[view-component-name]>
17:750
17:751
Parameter names must match the ones used in the view component method. However, both the component’s name and parameter names must be translated into kebab case; that is, all the characters must be transformed into lowercase if all the characters in the original name were in uppercase, although the first letter of the name must be preceded by a -. For instance, MyParam must be transformed into my-param.
17:752
Actually, view components are either classes that derive from the ViewComponent class, classes decorated with the [ViewComponent] attribute, or classes whose names end with the ViewComponent suffix. When a component is invoked, the framework looks for either an Invoke method or an InvokeAsync method and passes it all the parameters that were defined in the component’s invocation. InvokeAsync must be used if the method is defined as async; otherwise, we must use Invoke.
17:753
The following code is an example of a view component definition:
17:754
public class MyTestViewComponent : ViewComponent
17:755
{
17:756
17:757
public async Task<IViewComponentResult> InvokeAsync(
17:758
int par1, bool par2)
17:759
{
17:760
var model= ....
17:761
return View(`ViewName`, model);
17:762
}
17:763
17:764
}
17:765
17:766
The previously defined component must be invoked with a call such as the following:
17:767
<vc:my-test par1=`10` par2=`true`></vc:y-test>
17:768
17:769
If the component is invoked by a view of a controller called MyController, ViewName is searched for in the following paths:
17:770
17:771
/Views/MyController/Components/MyTest/ViewName
17:772
/Views/Shared/Components/MyTest/ViewName
17:773
17:774
Understanding the connection between ASP.NET Core MVC and design principles
17:775
The whole ASP.NET Core framework is built on top of the design principles and patterns that we analyzed in Chapter 11, Applying a Microservice Architecture to Your Enterprise Application, Chapter 13, Interacting with Data in C# – Entity Framework Core, Chapter 6, Design Patterns and .NET 8 Implementation, Chapter 7, Understanding the Different Domains in Software Solutions, and Chapter 5, Implementing Code Reusability in C# 12.
17:776
Moreover, all framework functionalities are provided through DI so that each of them can be replaced by a customized counterpart, without it affecting the remainder of the code. Moreover, these providers are not added individually to the DI engine; instead, they are grouped into collection properties of option objects (see the Loading configuration data and using it with the options framework subsection) for improved maintainability, and to conform to the Separation of Concerns principle, which is a generalization of the Single Responsibility principle. In fact, the order in which providers are added to their collection does matter, since they are processed in the same order as they are in the collection. Moreover, the effect of a provider also depends on the other providers that belong to the same collection, so sometimes, it is not enough to replace a provider or add a new provider, but it is necessary to also remove/replace other providers to remove their side effects.
17:777
Examples of providers grouped in collections include all model binders, validation providers, and data annotation providers.
17:778
Moreover, configuration data, instead of being available from a unique dictionary created from a configuration file, is organized into option objects thanks to the options framework we described in the first section of this chapter. This is also an application of the SOLID Interface Segregation principle.
17:779
However, ASP.NET Core also applies other patterns that are specific instances of the general Separation of Concerns principle, which (as mentioned earlier) is a generalization of the Single Responsibility principle. They are as follows:
17:780
17:781
The middleware modules architecture (the ASP.NET Core pipeline)
17:782
Factoring out validation and globalization from the application code
17:783
The MVC pattern itself
17:784
17:785
We will analyze each of these in the various subsections that follow.
17:786
Advantages of the ASP.NET Core pipeline
17:787
The ASP.NET Core pipeline architecture has two important advantages:
17:788
17:789
All the different operations that are performed on the initial request are factored out into different modules, according to the Single Responsibility principle.
17:790
The modules that perform these different operations don’t need to call each other because each module is invoked once and for all by the ASP.NET Core framework. This way, the code for each module is not required to perform any action that is connected to responsibilities that have been assigned to other modules.