Blazor Features missing in existing project

僤鯓⒐⒋嵵緔 提交于 2019-12-13 03:39:00

问题


I've started playing around with the new "Blazor Server App" project template in VS 2019 and everything works as expected. Now I've tried to use some Blazor stuff in an existing .NET Core 3 ASP.NET MVC app. I've added ".MapBlazorHub(); & .AddServerSideBlazor();" to the startup class and

<script src="_framework/blazor.server.js"></script>

to the _layout file. The new razor component gets rendered as expected and the "OnInitialized()" method in the @code block is fired. But when I try to use a button click event nothing happens - not in the VS console - not in the browser console. After some hours of research I've found out that the syntax highlighting is different in the 2 projects:

Microsoft Blazor Server App template:

Existing project:

Also I found that the "Add - Razor Page..." context menu is only visibible in the MS template. But I can't find any differences in the csproject or the sln file.

I'm really stuck on this. Any ideas what I'm missing?


回答1:


As Andreas has said, you need to add a new _Imports.razor file in your folder( Views folder or your custom folder where you restore your razor components.

_Imports.razor:

@using Microsoft.AspNetCore.Components.Web

Structure:

Also I found that the "Add - Razor Page..." context menu is only visibible in the MS template. But I can't find any differences in the csproject or the sln file.

The MS template uses Pages folder and you could see Add- Razor Page option.

If you are using Razor Pages project there will be Add- Razor Page, since you are using MVC, the option does not exist.

If you use the latest vs 2019 and asp.net core 3.0, you could create a razor component by clicking Add - New Item - Razor Component directly




回答2:


In the Blazor-Template-Project you should see a _Imports.razor file containing multiple @using directives.

Try adding the following directive to the Views\_ViewImports.cshtml file in your MVC app.

@using Microsoft.AspNetCore.Components.Web

Without the using directive the razor engine doesn't know the @onclick should be interpreted as C# code and therefor does not wire up the event handler as expceted. That's also why VisualStudio does not highlight it as C# syntax.

If this helps, you should probably also add the other blazor relevant @using directives to the _ViewImports.cshtml file.

Don't know about the missing 'Add - Razor Page...', sry.



来源:https://stackoverflow.com/questions/58436408/blazor-features-missing-in-existing-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!