gpt4 book ai didi

c# - Blazor - 如何获取布局 @Body 路径?

转载 作者:行者123 更新时间:2023-12-03 08:22:58 26 4
gpt4 key购买 nike

我正在解决面包屑导航和动态显示的问题(我想避免每个 Razor 组件(页面之一)中都有静态数据。谢谢您。

问题:如何获取@Body组件的路径?正文中当然是(项目中的默认文件夹名称)Pages之一。所以“body本身”的第一行是@page“/somePage”...

我的(缩短的)布局:

<div class="page">
<div class="main">
<div class="top-row TitleButtonList @((closedLeftBar) ? "TitleButtonListClose" : "") ">
<TitleButton />
</div>
<div class="top-row">
<BreadcrumbNav breadCrumbData="breadCrumbDatas"></BreadcrumbNav>
<p>Error test name: @path</p>
</div>

<div class="content px-4 @((closedLeftBar) ? "contentClose col-md-10" : "contentOpen col-md-9")">
@Body
<FOLButtons />
</div>
</div>
</div>

@code {
public List<BreadCrumbData> breadCrumbDatas;
string path = string.Empty;

protected override void OnInitialized()
{
breadCrumbDatas = breadCrumbService.GetProperList();
path = ??????
}
}

面包屑模型:

public class BreadCrumbData
{
[Required]
public string Text { get; set; }
[Required]
public string URL { get; set; }
[Required]
public int Level { get; set; }

[Required]
#nullable enable
public string? ParentURL { get; set; }

public BreadCrumbData(string text, string url, int level, string parentURL)
{
Text = text;
URL = url;
Level = level;
ParentURL = parentURL;
}
}

面包屑组件(布局中的那个组件)

<nav aria-label="breadcrumb">
<ol class="breadcrumb">
@if (breadCrumbData != null)
{

@foreach (var item in breadCrumbData)
{
@if (item == breadCrumbData.Last())
{
<li class="breadcrumb-item active" aria-current="page">@item.Text</li>

}
else
{
<li class="breadcrumb-item"><a href="@item.URL">@item.Text</a></li>
}
}
}
</ol>
</nav>

@code {
[Parameter]
public List<BreadCrumbData> breadCrumbData { get; set; }
}

最佳答案

Blazor 为此提供了 NavigationManager(请参阅 Blazor routing):

@inject NavigationManager NavigationManager;

protected override void OnInitialized()
{
breadCrumbDatas = breadCrumbService.GetProperList();

// Get everything after the domain + '/' (e.g. after "https://example.com/")
path = NavigationManager.Uri.Substring(Navigator.BaseUri.Length);

// You can also listen for a path change by subscribing to
// NavigationManager.LocationChanged.
}

一些注释/建议:

  • 由于 NavigationManager 可以被注入(inject),因此您不需要将其作为参数传递给 BreadCrumbs 组件(除非您将该组件用于除URL 路径)。您可以将其直接注入(inject)到您的 BreadCrumbs 组件中:
@inject NavigationManager NavigationManager;

<nav aria-label="breadcrumb">
<ol class="breadcrumb">
  • @Body 不是一个组件:它是一个 RenderFragment .
  • @Body 本身没有路径;页面(用 @page 指定)即可。路由由App.razor管理并在Startup.cs中配置。

关于c# - Blazor - 如何获取布局 @Body 路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67315618/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com