【问题标题】:Can't set parameter with type of base class by value of derived class无法通过派生类的值设置具有基类类型的参数
【发布时间】:2021-09-10 08:14:38
【问题描述】:

组件:

...
[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.

预期:

接受派生类代替基类

【问题讨论】:

  • [礼貌] 有点简洁。我没有看到你想要达到的目标。你在哪里定义&lt;component type="typeof(...)" param-InitialModel="@(new Derived())" render-mode="WebAssemblyPrerendered" /&gt;
  • 您是否找到了有关此问题的解决方案或更多信息?我也面临同样的问题...

标签: blazor


【解决方案1】:

我遇到了类似的问题,我刚刚解决了。

我必须在服务 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

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 1970-01-01
    • 2021-07-06
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    相关资源
    最近更新 更多