What is Blazor WebAssembly?
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.
What is .NET MVC (Model-View-Controller)?
.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 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 (<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 respectively.
First, we need to create a new ASP.NET Core Web Application project from the ASP.NET Core Web App (Model-View-Controller) template.
Next, create the Blazor WebAssembly project from the Blazor WebAssembly App template, and uncheck all options in the 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.
If we run the .NET MVC application now, we will see a default app with a navigation menu and some sample pages.
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 the .NET MVC project, add app.UseBlazorFrameworkFiles().
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 configures the application to serve Blazor WebAssembly framework files from the root path "/".
Disable Blazor WebAssembly default root components
By default, Blazor WebAssembly will use a root component to specify 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 an error. So, remove or comment on these lines in the Program.cs file in Blazor WebAssembly project:
// 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.
@{
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 uses 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.
Change the render mode to WebAssembly and re-run the application. We will see the same view result. But if you open the browser developer tool, you will see the Counter component is rendered after the page loaded, not served 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.
Continue reading about Combining Blazor WebAssembly and .Net MVC application. Please read the next article of the series here: Combining Blazor WebAssembly and .Net MVC application - part 2