Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor routing and layout when inside an area

I have an existing MVC project and I am trying to integrate Blazor into it. To do this I had to upgrade from .NET Core 2.1 to 3.1 and change a few things in my startup class to get the application working as it was before.

After sorting all the upgrade stuff out, I've now added the hub to my Configure startup method:

...

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "areas",
        pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

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

    endpoints.MapControllers();
    endpoints.MapRazorPages();
    endpoints.MapBlazorHub();
});

... and the server sign Blazor services registration:

...

services
    .AddMvc(options =>
    {
        ...
    })
    .AddRazorOptions(o =>
    {
        ...
    })
    .AddRazorPagesOptions(options =>
    {
        ...
    });

services.AddServerSideBlazor();

Finally, I've added the Blazor JS script to my ~/Pages/Shared/_Layout.cshtml view:

<script src="~/_framework/blazor.server.js"></script>

I'm struggling to figure out what the @page value should be for a new Razor Component when the component is within a view.

Here is my folder structure:

enter image description here

Everything inside the Pages folder is new.

Here is the contents of Index.razor:

@page "/"

<h3>Sales Homepage</h3>

@code {

}

I've tried the following for the @page route value:

  • "/"
  • "/Index"
  • "/Pricing/Sales/"
  • "/Pricing/Sales/Index"

None of these have worked - I just get a page not found error.

I'm also not sure how I'm supposed to use my existing layout in ~/Pages/Shared/_Layout.cshtml with these new components.

I've had a look at the scaffolded Blazor template project in Visual Studio and also checked the docs but haven't found this particularly useful as it's all focused on brand new Blazor projects.

like image 412
Andy Furniss Avatar asked Dec 20 '19 16:12

Andy Furniss


People also ask

How do you navigate from one page to another in Blazor?

You can redirect to a page in Blazor using the Navigation Manager's NavigateTo method. In the following code snippet, it will redirect to the home page when this page gets loaded. Similarly, you can call NavigateTo() method from NavigationManager class anywhere to redirect to another page.

How do you navigate to another page in Blazor with parameter?

By using Blazor route parameters, you can pass values from one page to another page. Use NavigationManager to pass a value and route the parameter to another page. Follow this example to achieve passing values from one page to another. Get the passed Page1 parameter value in Page2.

How does Routor work in Blazor?

The Router component enables routing to Razor components in a Blazor app. The Router component is used in the App component of Blazor apps. When a Razor component ( . razor ) with an @page directive is compiled, the generated component class is provided a RouteAttribute specifying the component's route template.


2 Answers

To add blazor pages support, you also need to add call to MapFallbackToPage (for Razor Pages project) or MapFallbackToController(for MVC project) in startup endpoint configuration.

For MVC project, refer to below steps:

1.Create a App.razor under Views folder

@using Microsoft.AspNetCore.Components.Routing

<Router AppAssembly="typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="routeData" />
    </Found>
    <NotFound>
        <h1>Page not found</h1>
        <p>Sorry, but there's nothing here!</p>
    </NotFound>
</Router>

2.Create a _Host.cshml file under Views/Shared

@page "/blazor"

@{
    Layout = "_Layout";
}

<app>
    @(await Html.RenderComponentAsync<App>(RenderMode.ServerPrerendered))
</app>

MyApp

——Views

————Shared

——————Host.cshtml

————App.razor

3.Add call to MapFallbackToController and point it to the new _Host.cshtml:

app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
            endpoints.MapBlazorHub();
            endpoints.MapFallbackToController("Host","Home");
        });

HomeController:

public class HomeController : Controller
{
    public IActionResult Host()
    {
        return View("_Host");
    }
}

4.Index.razor test with "/"

@page "/"

<h3>Sales Homepage</h3>

For Razor Pages project, just create _Host.cshtml and App.razor under Pages folder, and use endpoints.MapFallbackToPage("/_Host") in startup.cs

More clear steps,refer to https://mikaelkoskinen.net/post/combining-razor-blazor-pages-single-asp-net-core-3-application

like image 102
Ryan Avatar answered Oct 22 '22 08:10

Ryan


You must:

  1. Define another namespace for Areas/Pages to prevent name conflict with main branch without Areas.

  2. Place to you Areas new App.razor component. The same if layout is the same.

  3. Place your page with @route attribute on top of each page in Areas/Pages and Areas/Shared

  4. Place _Host.rasor, the same if layout is the same. But you must changing href attibutes in header (add ~).

  5. Add to startup new route

endpoints.MapAreaControllerRoute("admin_route", "Admin", "Admin/{controller}/{action}/{id?}");
  1. Main point to hope to Areas is: you must break existing SignalR connection and navigate to Areas not from simple click, but the same way
navigationManager.NavigateTo("/Admin/", forceLoad: true);

This is workable pattern, I always use it and it working fine.

like image 45
Viacheslav Avatar answered Oct 22 '22 06:10

Viacheslav