首页 > 解决方案 > 无法通过派生类的值设置具有基类类型的参数

问题描述

零件:

...
[Parameter]
public Base InitialModel {get;set;}
...

模型:

record Base() {}
record Derived():Base {}

用法:

<component type="typeof(...)" param-InitialModel="@(new Derived())" render-mode="WebAssemblyPrerendered" />

.....

结果:

System.InvalidOperationException: The parameter 'InitialModel with type 'Base' in assembly '...' could not be found.

预期的:

接受派生类代替基类

标签: blazor

解决方案


我有一个类似的问题,我刚刚解决了它。

我必须在服务 DI 系统中注册课程。在 WASM 项目中编辑 program.cs 文件以将类添加到服务中

      public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            //builder.RootComponents.Add<App>("#app");

            builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
            builder.Services.AddScoped<MyViewModel, MyViewModel>();   // <= add this line

            await builder.Build().RunAsync();
        }

相关问题:How to pass ViewModels into Razor Components in .NET Core 3.1


推荐阅读