【问题标题】:.NET 5 Routing with Parameters.NET 5 带参数的路由
【发布时间】:2021-09-28 14:04:26
【问题描述】:

我有两个简单的页面,想将一些参数从一个传递到下一个。当前代码出现错误:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] 未处理的异常呈现组件:无法在“PortalUI.Pages.CategoriesPage”类型的对象上设置属性“ManufacturerID”。错误是:指定的转换无效。 System.InvalidOperationException:无法在“PortalUI.Pages.CategoriesPage”类型的对象上设置属性“ManufacturerID”。错误是:指定的转换无效。 ---> System.InvalidCastException: 指定的强制转换无效。

页面如下(按执行顺序)

@page "/machines/manufacturers"
@inject HttpClient Http
@inject NavigationManager NavManager

<h1>Manufacturers</h1>

<p>Display all manufacturers in the database</p>

@if (manufacturers == null)
{
    <p><em>Loading...</em></p>
}
else
{
    @foreach (var i in manufacturers)
    {
        <a @onclick="((args) => Navigate(i.ManufacturerID))">
            <ManufacturersBox Name="@i.Name"
                              ImgURL="@i.ImgURL" />
        </a>
    }
}

@code {
    private Manufacturers[] manufacturers;

    protected override async Task OnInitializedAsync()
    {
        manufacturers = await Http.GetFromJsonAsync<Manufacturers[]>("https://localhost:44335/api/Manufacturers");
    }

    private void Navigate(int ManufacturerID)
    {
        NavManager.NavigateTo($"/machines/manufacturers/{ManufacturerID}/categories");
    }
}

以及我要传递到的页面

@page "/machines/manufacturers/{ManufacturerID}/categories/"

@inject HttpClient Http
@inject NavigationManager NavManager

<h3>CategoriesPage</h3>

<p>This page belongs to @ManufacturerID</p>

@code {
    [Parameter]
    public int ManufacturerID { get; set; }

    private Categories[] categories;

    protected override async Task OnInitializedAsync()
    {
        categories = await Http.GetFromJsonAsync<Categories[]>("https://localhost:44335/api/ManufacturerCategories/" + ManufacturerID);
    }
}

我尝试在链接中使用 href 而不是使用 NavigationManager(我更喜欢它,因为它允许用户在点击之前查看屏幕底部的 URL),但两者都给出了相同的答案。

现在考虑到我没有收到 .NET 的默认 404 Page not Found 错误,我假设发生了一些事情,我只是在某个地方搞砸了。

附加信息:
我的 UI 是 Blazor WebAssembly 应用程序
我的业务逻辑是您可以在 OnInitializedAsync() 看到的 API

【问题讨论】:

  • 另外,@ErikPhilips。感谢您的编辑,以后会记住的。

标签: c# asp.net-core blazor asp.net-mvc-routing asp.net-core-5.0


【解决方案1】:

你需要设置@page如下:

@page "/machines/manufacturers/{ManufacturerID:int}/categories/"

Router 从 url 中提取参数作为字符串并将其传递给 RouteView 组件,该组件尝试将字符串作为 ManufacturerID 参数传递给组件。

上述更改告诉路由器将值捕获为 int。

见 - Ms Docs - Route Constraints

【讨论】:

  • 谢谢,真的是这样。我也换成了 href 而不是 NavigationManager。最后一个问题,因为他们在文档中并没有真正说出来。为什么没有约束它就不起作用?传递的值仍然是一个整数,它只是不知道它是一个?
  • 查看我的更新答案。路由参数有两种方法 - 告诉路由器将“字符串”转换为什么,或者总是将它们作为字符串传递,然后自己进行转换/转换为内部属性。
猜你喜欢
  • 2015-04-17
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 2014-12-09
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多