首页 > 解决方案 > 如何在视图模型中使用路由参数?

问题描述

我的 Razor 组件是这样开始的:

@page "/track/{TrackId}"
@using BlazorSPA1.ViewModels
@inject ITrackViewModel TrackViewModel

我的 TrackViewModel 有一个公共属性 TrackId:

[Parameter]
public string TrackId { get; set; }

问题是我的 View vodel 中的 TrackId 属性被忽略了。我会得到以下异常:

错误:System.InvalidOperationException:“BlazorSPA1.Pages.Track”类型的对象没有与名称“TrackId”匹配的属性。Microsoft.AspNetCore.Components.Reflection.ComponentProperties.ThrowForUnknownIncomingParameterName(Type targetType, String parameterName) Microsoft.AspNetCore.Components.Reflection.ComponentProperties.SetProperties(ParameterView& parameters, Object target) Microsoft.AspNetCore.Components.ParameterView.SetParameterProperties(Object target) 在 Microsoft.AspNetCore.Components.ComponentBase.SetParametersAsync(ParameterView parameters) 在 Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterView 参数) 在 Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(DiffContext& diffContext,1 oldTree, ArrayRange1 newTree) 在 Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderInExistingBatch(RenderQueueEntry renderQueueEntry) 在 Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue ()

摆脱这种异常的唯一方法是直接在我的 razor 组件中定义属性:

@functions {
        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();
            await TrackViewModel.OnInitialyzeAsync();

        }

        [Parameter]
        public string TrackId { get; set; }
}

有没有办法使用我的视图模型中的属性来完成这项工作?

标签: c#asp.net-coreblazorblazor-server-side

解决方案


推荐阅读