I'm trying to use Blazor in a .net core 3 MVC project. I used a few tutorials to do this, like https://fizzylogic.nl/2019/08/18/integrating-blazor-in-an-existing-asp-net-core-application/ and https://chrissainty.com/using-blazor-components-in-an-existing-mvc-application/ .
What is working: The initialization of the Blazor component is working. The OnInitializedAsync() function gets triggered and the component gets rendered fine.
This is the call from the MVC View:
@(await Html.RenderComponentAsync<MyProject.Components.Locations>(RenderMode.ServerPrerendered))
What isn't working: using @onclick in the Blazor component. This is some sample code:
<span @onclick="AddLocation"></span>
@code {
private void AddLocation(){
}
}
The reason it probably doesn't work is that I get errors in the initialization of the connection. The component gets rendered not from the base path, but from the url of the specific view, and I think that messes with the connection. I receive these errors in the console of Chrome:
- [2019-12-02T09:26:08.117Z] Information: Normalizing '_blazor' to 'https://localhost:44375/Locations/_blazor'. _blazor/negotiate:1 Failed to load resource: the server responded with a status of 404 () blazor.server.js:1
- [2019-12-02T09:26:08.155Z] Error: Failed to complete negotiation with the server: Error e.log @ blazor.server.js:1 blazor.server.js:1
- [2019-12-02T09:26:08.156Z] Error: Failed to start the connection: Error e.log @ blazor.server.js:1 blazor.server.js:15
- [2019-12-02T09:26:08.156Z] Error: Error e.log @ blazor.server.js:15 blazor.server.js:1 -Uncaught (in promise) Error: Cannot send data if the connection is not in the 'Connected' State.
The main fault is probably the 'Normalizing '_blazor' to 'https://localhost:44375/Locations/_blazor''. Requesting _blazor from the base path works. Does anyone know how to set the basepath in such a situation?
(Yes, Blazor in a normal Razor page environment is probably easier, but I want to try Blazor in MVC.)
edit 1
<base href="/" />
in the header seems to have fixed the errors in the console. I hoped it would fix the onclick issue, but not yet... I think the component gets somehow treated like a normal razor component, and not as a blazor component. If I look at the generated html, I can find this: <span @onclick="AddLocation" ></span>
, and I think that is wrong (with a normal razor/blazor project, the @onclick dissapears from the html). Anyone knows the solution for this? Tried this: https://stackoverflow.com/a/58444907/1794246 , but that didn't do much.
edit 2
Having a _imports.razor file in the root of the MVC project did obviously nothing. Adding these using statements to the Blazor component actually fixed the problem with the onclick (also Intellisense recognized things in the component a bit better):
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Web;
<head> <base href="/" />
– agua from mars