Google Code Prettify

Razor 元件可以整合到 Razor Pages、MVC

在 ASP.NET Core MVC 中整合 Razor 元件(Razor Components)是可能的,這允許你利用 Blazor 的優勢,
並將其嵌入到現有的 MVC 或 Razor Pages 應用中。以下是如何在 ASP.NET Core MVC 應用中整合和使用 
Razor 元件的步驟:


### 步驟 1:設置專案

1. 確保你的 ASP.NET Core MVC 專案已經包含 Blazor Server 的支持。如果還沒有,你需要安裝相關的
 NuGet 套件:


dotnet add package Microsoft.AspNetCore.Components.Web
dotnet add package Microsoft.AspNetCore.Components.WebAssembly.Server

2. 確保在 `Startup.cs` 中配置 Blazor Server。

### 步驟 2:配置 `Startup.cs`

在 `Startup.cs` 文件中,添加 Blazor Server 的配置。


public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor(); // 添加這一行
    services.AddControllersWithViews();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

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

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapBlazorHub(); // 添加這一行
        endpoints.MapFallbackToPage("/_Host"); // 添加這一行
    });
}


### 步驟 3:創建 Razor 元件

在你的專案中創建一個新的 Razor 元件,例如 `MyComponent.razor`。


<!-- MyComponent.razor -->
@page "/mycomponent"

<h3>Hello from MyComponent</h3>

<p>Current count: @currentCount</p>
<button @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}


### 步驟 4:創建 `_Host.cshtml` 文件

在 `Pages` 文件夾中創建一個 `_Host.cshtml` 文件。這個文件是 Blazor Server 的入口點。


@page "/_Host"
@namespace YourNamespace.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Blazor Server</title>
    <base href="~/" />
    <link href="css/site.css" rel="stylesheet" />
</head>
<body>
    <app>
        <component type="typeof(App)" render-mode="ServerPrerendered" />
    </app>

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


### 步驟 5:創建 `App.razor` 文件

在 `Pages` 文件夾中創建一個 `App.razor` 文件,並設置路由。


<!-- App.razor -->
<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="routeData" Selector="h1" />
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>


### 步驟 6:在 MVC View 中使用 Razor 元件

你可以在 MVC View 中使用 Blazor 元件,這需要將 Blazor 元件嵌入到你的 MVC 頁面中。

首先,創建一個 MVC View,例如 `Views/Home/Index.cshtml`:


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

<div>
    <h1>Welcome to ASP.NET Core MVC with Blazor</h1>
    <component type="typeof(MyComponent)" render-mode="ServerPrerendered" />
</div>


確保你已經在 `_ViewImports.cshtml` 中添加了以下指令:


@using YourNamespace
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Microsoft.AspNetCore.Components.Web


### 步驟 7:運行應用

現在,你應該能夠運行應用並在 MVC 頁面中看到 Blazor 元件的內容。

### 總結

通過這些步驟,你已經成功地在 ASP.NET Core MVC 應用中整合了 Blazor 元件。這樣,你可以在現有的
 MVC 應用中利用 Blazor 的強大功能來構建互動性更強的用戶界面。