在Blazor中创建href到子页面



我的页面有这个指令@page "/sales/reports",所以它在https://localhost/sales/reports路由加载。

我想创建链接<a href="">Report 1</a>,这将导致子页面/sales/reports/{id}-例如https://localhost/sales/reports/8c5b8c1c-12b5-43ee-92c9-8d3bcb8644a4,但不确定我把我的锚的href。当我简单地把<a href="@myGuid">Report 1</a>链接有一个形式的https://localhost/8c5b8c1c-12b5-43ee-92c9-8d3bcb8644a4。我需要硬编码<a href="sales/reports/@myGuid">Report 1</a>还是有更聪明的方法?

"子页面"这个词并不存在。

只有"页面"one_answers"路由"。有时路由出现嵌套,如在你的例子中,但这并不使它成为一个'子页'。

你的问题的答案是,是的,你需要包括到你想去的"页面"的路由。

<a href=@($"sales/reports/{@myGuid}")>Report 1</a>

这并不一定意味着在页面本身进行硬编码。您可以创建一个助手类来为您完成这些工作。例如:

class ReportPathCreator
{
public static string ReportRouteFor(Guid reportGuid) => $"sales/reports/{reportGuid}";
}

然后使用:

<a href=@(ReportPathCreator.ReportRouteFor(myGuid))>Report 1</a>

然后,如果你选择改变报告所在的路由,你只需要在helper类中改变它,你站点中的所有锚元素都会自动选择这个新路由。

你也可以使用静态类生成一个模板来代替@page指令:

class ReportPathCreator
{
public static string ReportRouteFor(Guid reportGuid) => $"sales/reports/{reportGuid}";
public static string ReportTemplate = "sales/reports/{reportGuid:guid}";
}

然后,用:

代替@page指令
@attribute [Route(ReportPathCreator.ReportTemplate)]

最新更新