Combining Blazor WebAssembly and .Net MVC application - part 1
Tags: blazor, webassembly, dotnet, csharp
Published: 2023-08-11 08:28:55

**Blazor WebAssembly** is a framework for building interactive web applications using C# and HTML. It allows you to run C# code directly in the browser, without relying on JavaScript or plugins. Blazor WebAssembly is one of the hosting models for Blazor, along with Blazor Server and Blazor Hybrid.

**.NET MVC (Model-View-Controller)** is a design pattern for building web applications using ASP.NET Core. It separates the application into three components: the model, which represents the data and business logic; the view, which displays the user interface; and the controller, which handles the user requests and interactions.

In this blog post, I will show you how to combine Blazor WebAssembly and .NET MVC in a single application. This can be useful if you want to leverage the benefits of both frameworks, such as:

- Using C# for both client-side and server-side code, which simplifies development and maintenance.
- Taking advantage of Blazor's rich component model and interactivity, which enhances the user experience.
- Using .NET MVC's routing, authentication, authorization, and dependency injection features, which provide security and flexibility.

The key to combining Blazor WebAssembly and .NET MVC application is the [Component Tag Helper](https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/component-tag-helper?view=aspnetcore-7.0) (`<component>` tag). The component tag helper is used to render Blazor components in your MVC views. By using the component tag, you can easily integrate Blazor components into your existing MVC application.

## Creating the Application

To create the application, we will use Visual Studio. You can download them from [here](https://visualstudio.microsoft.com/downloads/) respectively.

First, we need to create a new **ASP.NET Core Web Application** project from `ASP.NET Core Web App (Model-View-Controller)` template.

Next, create the **Blazor WebAssembly** project from `Blazor WebAssembly App` template, uncheck all options in next dialog.

Now, we need to add the Blazor WebAssembly project as a reference to your existing .NET MVC application. Right-click on your .NET MVC project in the Solution Explorer and select **Add** -> **Project Reference**. In the **Reference Manager** dialog box, select the **Projects** tab and then select your **Blazor WebAssembly** project.

![Creating visual studio application solution](https://cdn.freemailforward.net/assets/images/uploaded/blog/create-solution-1.webp)

If we run the .NET MVC application now, we will see a default app with a navigation menu and some sample pages.

![Default solution view](https://cdn.freemailforward.net/assets/images/uploaded/blog/create-solution-3.webp)

## Config to serve Blazor WebAssembly in .NET MVC application

### Adding Blazor files in .NET MVC project

First, we need to add `Microsoft.AspNetCore.Components.WebAssembly.Server` package to .NET MVC project. 

Then, in the **Program.cs** file in .NET MVC project, add `app.UseBlazorFrameworkFiles()`:

```csharp
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.UseBlazorFrameworkFiles();

app.Run();

```

This method to configure the application to serve Blazor WebAssembly framework files from the root path "/".

### Disable Blazor WebAssembly default root components

By default, Blazor WebAssembly will use root component to specifies where the root App component is rendered. The component is rendered at the location of the `div` DOM element with an `id` of `app` `(<div id="app">Loading...</div>)`. If the DOM element does not exist, Blazor WebAssembly will run error. So, remove or comment these lines in the **Program.cs** file in Blazor WebAssembly project:
```csharp
//builder.RootComponents.Add<App>("#app");
//builder.RootComponents.Add<HeadOutlet>("head::after");
```

## Using Blazor Components in MVC Views

One of the advantages of combining Blazor WebAssembly and .NET MVC is that we can use Blazor components in MVC views. This allows us to create dynamic and interactive web pages using C# and HTML.

For example, let's reference the **Counter** component in the **Index** view. To do this, we need to modify the code of the **Index.cshtml** file under the **Views/Home** folder as follows:

```html
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

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

@section Scripts{
    <script src="_framework/blazor.webassembly.js"></script>
}
```

This code use **Component Tag Helper** to render the **Counter** component, specifying its type and render mode. The render mode can be one of the following:

- **WebAssembly**: The component is rendered by Blazor WebAssembly in the browser after the page is loaded.
- **WebAssemblyPrerendered**: The component is rendered by Blazor WebAssembly on the server as part of the page, and then transferred to the browser where it is connected to Blazor WebAssembly.

Now, if we run the application, we will see the component displayed by our view.

![MVC page with component](https://cdn.freemailforward.net/assets/images/uploaded/blog/create-blazor-app-3.webp)

Change the `render-mode` to **WebAssembly** and re-run the application, web will see same view result. But if open browser developer tool, you will see the **Counter** component is rendered after the page loaded, not serve in the request response.

We can reference more Blazor components in more MVC views, following the same steps.

## Conclusion

In this blog post, I have shown you how to combine Blazor WebAssembly and .NET MVC in a single application. This can be a powerful way to create web applications that use C# for both client-side and server-side code, and that take advantage of Blazor's interactivity and .NET MVC's features.

I hope you have found this blog post useful and interesting please share it with your friends. Thank you for reading.

This post use the Visual Studio 2022 and .NET 7.0, use other version may not working. Link to full post at [here](https://freemailforward.net/combining-blazor-webassembly-and-net-mvc-application-part-1).