【发布时间】:2020-02-18 16:54:10
【问题描述】:
我已经编辑了整个问题以便更好地理解
我的示例解决方案包含 2 个项目
- MVC 应用程序 + Blazor 服务器
- Razor 类库
Razor 类库有一个非常简单的组件“Awesome.razor”:
<h3>@name</h3>
<button @onclick="@(() => name = name.ToUpper())">Upper case me</button>
@code {
string name = "Mr. Blazor";
}
MVC 应用有一个 Home/Index.cshtml:
看起来像这样:
<div id="MyComponent">
@(await Html.RenderComponentAsync<Awesome>(RenderMode.ServerPrerendered))
</div>
如果我运行应用程序 (<root>/home/index)
我可以点击按钮,Awesome 组件就可以工作了。
我是否可以使用相同的技术 (Html.RenderComponentAsync) 但不使用 Blazor Server 来使用 Blazor WebAssembly?
我做了一些尝试使其工作(通过使用 Blazor WebAssembly 的模板并将其与 MVC 应用程序集成来尝试/出错),但无法使其工作。我想知道我是否做错了什么,或者RendercomponentAsync 是否只能与 Blazor Server 结合使用。
完整的源代码可以在这里找到(我没有尝试 WebAssembly): https://github.com/geeForceOne/MvcWithBlazor
更新
显然 Blazor WebAssembly 中支持 RenderComponentAsync。
通过将他的示例应用程序改编为https://github.com/geeForceOne/BlazorWebAssemblyWithPrerendering,我设法部分实现了我想要的(感谢Daniel Roth)。
我尝试了不同的尝试 n 错误并想出了这个解决方案:
在 Blazor.Client 项目的 Startup.cs 中,我注册了两个组件:
app.AddComponent<Counter>("counter");
app.AddComponent<Awesome>("awesome");
然后我创建了两个 Razor 页面 MyTest.cshtml 和 MyTest2.cshtml。虽然 MyTest.cshtml 完全符合我的要求并且工作正常:
<awesome>
@(await Html.RenderComponentAsync<Awesome>(RenderMode.Static))
</awesome>
<counter>
@(await Html.RenderComponentAsync<Counter>(RenderMode.Static))
</counter>
<script src="_framework/blazor.webassembly.js"></script>
它不适用于 MyTest2.chshtml
@* To make this work, you need to
call
app.AddComponent<Awesome>("awesome");
before
app.AddComponent<Counter>("counter");
in
BlazorWebAssemblyWithPrerendering.Client.Startup
*@
<awesome>
@(await Html.RenderComponentAsync<Awesome>(RenderMode.Static))
</awesome>
<script src="_framework/blazor.webassembly.js"></script>
我的问题:我是否走在正确的道路上(我需要进行哪些更改才能使其正常工作)?或者我可以按照 Daniel Roth 的原始示例以这种方式只运行一个组件吗?
【问题讨论】:
-
在看到您的示例应用程序后,我删除了旧答案并添加了新答案...
标签: asp.net-core razor blazor blazor-server-side blazor-client-side