Reputation: 5692
I've successfully done this with a .NET Core 5 Mvc app, delivering a separate Blazor WebAssembly SPA from a razor pages site. I'm using the tag helper and am manually referencing the _framework/blazor.webassembly.js file. It nicely keeps the razor pages layout and delivers the SPA seamlessly within the razor pages site and is fully interactive.
Because webassembly is run entirely in the browser, I'm curious if there's a way to do the same with a .NET Framework 4.8 MVC app. I would think that all the MVC app needs to provide is access to the _framework/*.js files to boot up the Blazor app.
The Blazor project targets .NET Standard 2.1 so I don't really see why it wouldn't be possible. .NET Framework 4.8 just needs the equivalent of RenderComponentAsync. Does this exist?
Upvotes: 7
Views: 2722
Reputation: 136
It's definitely possible, you have two choices available here.
You can serve the whole index.html that Blazor WASM produces when you publish as Blazor WASM is just static files. The downside of this is Blazor will have to take over the whole site like a typical SPA project. Not an incremental approach that one might prefer.
Another possible way that is nearer to what you want is through the new Blazor feature for .Net 6. Which is instantiating Blazor components from Javascript. With this and a bit of Javascript, you can render Blazor WASM components on .Net Framework MVC even with parameters.
Usage is a bit more involved, as it's a low level api for building features on top of it.
// Program.cs
builder.RootComponents.RegisterForJavaScript<Counter>(identifier: "blazor-counter");
// On your cshtml
<blazor-counter data-initial-count="@Model.InitialCount" />
// JS script to instantiate it
let containerElement = document.getElementsByTagName('blazor-counter')[0];
await Blazor.rootComponents.add(containerElement, 'blazor-counter', { initialCount: $(containerElement).data("initial-count") });
If you don't mind trying out preview packages, the Blazor team has an experimental package the builds upon that feature to support encapsulating that into standard HTML web components.
Usage then becomes as simple as this.
// Program.cs
builder.RootComponents.RegisterAsCustomElement<Counter>("blazor-counter");
// On your cshtml
<blazor-counter initial-count="@Model.InitialCount" />
The only thing this doesn't support is pre-rendering. As that needs an Aspnet Core server as a host.
Upvotes: 2