How to enable/use/configure WebAssembly Blazor in existing .NET MVC Project?
Asked Answered
A

2

20

I have a web application that is written in .net core MVC, a standard, "old school" web application using model/view/controller pattern. In this app I have a few complex forms which change based on user selection. Different elements load based on what user selected in the first few drop down lists. Currently I use Vue.js to successfully build such an interface. So basically I do not have a SPA app but I sporadically use Vue.js throughout my app when there is a need for a complex front end interface.

Now that client side WebAssembly Blazor is officially out, I would like to replace my complex forms written in vue.js with a Blazor based code. I've found the post that explains how to do this with server side Blazor here but I can't find anything with regards to WebAssembly version of it.

Has anyone managed to integrate client side - web assembly Blazor into an existing MVC project? If so how?

Ashlar answered 25/5, 2020 at 6:56 Comment(3)
Do you mean using UseMvc instead of UseEndpoints ?Adessive
I mean user MVC project as in controllers and views and models not the new Razor Pages project template but an MVC project template. All their examples start with Razor Pages project.Ashlar
I'm intrigued, @Marko, how did you resolve your problem, please?Knockwurst
A
13

To setup Blazor WASM to an existing project you need to :

  • Add a reference to the Blazor WASM project in your ASP.Net Core project
  • Add package reference to Microsoft.AspNetCore.Components.WebAssembly.Server
  • Add UseBlazorFrameworkFiles() in your middleware pipeline
  • Add UseStaticFiles() in your middleware pipeline
  • Add MapFallbackToFile to endpoints pointing to your Blazor WASM index.html
public void Configure(IApplicationBuilder app)
{
    if (Environment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage()
            .UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error")
            .UseHsts();
    }

    app.UseHttpsRedirection()
        .UseBlazorFrameworkFiles()
        .UseStaticFiles()
        .UseRouting()
        .UseAuthentication()
        .UseAuthorization()
        .UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
               name: "default",
               pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapFallbackToFile("index.html");
        });
}

Adessive answered 25/5, 2020 at 7:15 Comment(11)
Ok I've done all this but I still cannot use any Blazor components. For example I cannot just reference the Counter component from my Blazor project via a tag helper like <Counter /> inside my MVC views.Ashlar
Since this is about legacy projects it's worth noting you need >= asp.net Core 3Largeminded
It's an SPA app, you cannot use Blazor WASM component in your MVC View using a Tag helper. You can integrate the app in View, by adding same javascript and <App> tag than index.htmlAdessive
It's more or less the same than integrating an Angular or React APPAdessive
@HenkHolterman That's a server side blazor integration example using SingalR Blazor hubs. I want client side Blazor integration.Ashlar
@aguafrommars Are you saying I need javascript to run Blazor in MVC .net app? If that is the case then what's the point of even trying to integrate Blazor in my app? I find it hard to believe that in order to use WebAssembly Blazor I need to literally rebuild my entire app in Razor Pages...Ashlar
Again, it's an SPA app running in the browser not in the server. It's booted with _framework/blazor.webassembly.js. If you want to host the app in a .cshtml view you need this script exactly as index.html does. You don't need to rebuild the app. Blazor WASM is not related to Razor Pages nor MVC, it can run on a github page if you want or any http server serving static pages.Adessive
Read the doc : learn.microsoft.com/en-us/aspnet/core/host-and-deploy/blazor/…Adessive
Integrating server-side blazor is much easier in an mvc view/razor page. Perhaps the easiest way to add WebAssembly blazor to an existing app is through an <iframe> as it will let you point its src directly to the blazor app - it will be separate from the rest of your view anywayBergin
This was perfect for me adding a Blazor WASM to my existing .Net core Web API. Thanks!Unsling
@Marko, a web assembly written in ANY language, requires a spot of javascript to get it going. I've yet to see it embedded in a razor application, similar to a flash movie for instance, but that's what I'd like to do and it looks less and less like this might be possible.Knockwurst
K
6

I have this working and it's really made my week.

Firstly, update or convert your MVC project to .Net 5.0.402. It MAY work on an earlier version but I haven't tested it.

To your MVC solution, add a blazor web assembly app project. This is the web assembly components project.

On the MVC view, at the place you wish to render your blazor component add:

@using myawesomewasmprojectnamespace.Pages

<component type="typeof(Counter)" render-mode="WebAssemblyPrerendered"/>

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

The '@using' declaration refers to the blazor web assembly app project, Pages directory. The 'typeof(Counter)' type refers to the Counter.razor component in the default blazor web assembly app project, visual studio supplies. This may of course be swapped for the final design component.

In the MVC project's _Layout.cshtml, or wherever the <head> tag of the MVC view is, include in the <head> tag for every page with a blazor component in it:

<base href="/"/>

Add the 'Microsoft.AspNetCore.Components.WebAssembly.Server' package to your MVC project.

Add a reference to the blazor web assembly app project, in your MVC Dependencies, project references.

In the MVC apps Startup.cs, 'public void Configure(IApplicationBuilder app, IWebHostEnvironment env)' method, add the following:

app.UseBlazorFrameworkFiles();

In the blazor web assembly app project, Program.cs file, comment out the following line to stop the application looking for a '<div id="app"></div>'

//builder.RootComponents.Add<App>("#app");

Finally, delete the favicon from the blazor web assembly app project's wwwroot directory as it will clash with the MVC one.

This then adds the 'Counter' component to your MVC view.

To add a different component to a different view, insert it with:

@using myawesomewasmprojectnamespace.Pages

<component type="typeof(Myawsomecomponentnamecompletelydifferentfromanymvccontrolleroractionname)" render-mode="WebAssemblyPrerendered"/>

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

And start your blazor component with:

@page "/myawsomecomponentnamecompletelydifferentfromanymvccontrolleroractionname"

I'm so chuffed to get this working, as I've been trying for ages. If you can't get it working, please message me and I'll try to answer any questions.

Knockwurst answered 31/10, 2021 at 21:48 Comment(3)
How did you get the Blazor component to init on the client? Something is missingTransfuse
@Transfuse , I just created a brand new .Net core 5.0 MVC application in visual studio. I then added blazor web assembly app project to it and followed all the instructions above. Make sure you add the nuget package and the project dependency reference. I included the Counter.razor component on the default MVC project privacy page and it worked straight away. The javascript starts the web assembly in the component tag on the page. What error are you getting, please?Knockwurst
As for the rendering this solution works perfectly fine for me. But somehow the @onclick does not fire when clicking the counter button. Tried this solution (#59136721) but without any success (probably because the issue is referring to Blazor Server)Lockhart

© 2022 - 2024 — McMap. All rights reserved.