首页 > 解决方案 > 如何在 Blazor.Net 中从 UI 中分离代码

问题描述

参考这篇VisualStudioMagazine文章,我试图将代码放在单独的文件中,而不是 razor 视图中。

我试过:

@page "/Item"
@using WebApplication1.Shared
@using WebApplication1.Client.Services;
@inject HttpClient Http
@inherits ItemComponent

@if (ItemList != null)
{
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Category</th>
                <th>Metal</th>
                <th>Price</th>
                <th>Quantity</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in ItemList)
            {
                <tr>
                    <td>@item.ID</td>
                    <td>@item.Name</td>
                    <td>@item.Category</td>
                    <td>@item.Metal</td>
                    <td>@item.Price</td>
                    <td>@item.Quantity</td>
                </tr>
            }
        </tbody>
    </table>
}

@functions{
    public ItemModel[] ItemList;
    ItemComponent IC = new ItemComponent();

    protected override async Task OnInitAsync()
    {
        ItemList = IC.GetItems().Result;
        //ItemList = await Http.GetJsonAsync<ItemModel[]>("api/Item/GetItems");
        StateHasChanged();
    }
}

和项目组件:

using System.Threading.Tasks;
using WebApplication1.Shared;
using System.Net.Http;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Blazor;

namespace WebApplication1.Client.Services
{
    public class ItemComponent
    {
        public async Task<ItemModel[]> GetItems()
        {
            ItemModel[] ItemList;
            HttpClient Http = new HttpClient();
            ItemList = await Http.GetJsonAsync<ItemModel[]>("api/Item/GetItems");
            return ItemList;
        }

    }
}

但它不起作用,它表明:

严重性代码描述项目文件行抑制状态错误 CS0115 'Item.BuildRenderTree(RenderTreeBuilder)': 找不到合适的方法来覆盖 WebApplication1.Client D:\Other\blazor\WebApplication1.Client\obj\Debug\netstandard2.0\RazorDeclaration\Pages \ItemModule\Item.razor.g.cs 30 活动

同样根据教程页面不能继承BlazorComponentItemComponent因为它没有参考。

有什么方法可以将大部分代码从 Blazor 视图分离到单独的代码文件中?

更新 1

根据 Chris Answer 进行更改后,它显示异常

System.Net.Http.HttpRequestException:无法建立连接,因为目标机器主动拒绝了它。---> System.Net.Sockets.SocketException: 无法建立连接,因为目标机器主动拒绝。在 System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancelToken) --- 内部异常堆栈跟踪结束 --- 在 System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancelToken ) 在 System.Threading.Tasks.ValueTask 1.get_Result() 在 System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancelToken) 在 System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask
1.get_Result() at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask1.get_Result() 在 System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancelToken) 在 System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancelToken
) 在 System.Net.Http.HttpClient 1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at System.Net.Http.HttpClient.GetStringAsyncCore(TaskMicrosoft.AspNetCore.Builder.BlazorMonoDebugProxyAppBuilderExtensions.GetOpenedBrowserTabs(String debuggerHost) 上的.FinishSendAsyncUnbuffered(Task 1 getTask).AspNetCore.Builder.BlazorMonoDebugProxyAppBuilderExtensions.DebugHome(HttpContext context)

标签: c#blazor.net-core-3.0blazor-server-sideasp.net-core-3.0

解决方案


ComponentBase你只需要像这样在你的ItemComponent类中继承。

public class ItemComponent : ComponentBase
{
    public async Task<ItemModel[]> GetItems()
    {
        ItemModel[] ItemList;
        HttpClient Http = new HttpClient();
        ItemList = await Http.GetJsonAsync<ItemModel[]>("api/Item/GetItems");
        return ItemList;
    }
}

这篇文章有点过时了,因为BlazorComponent不久前改名了。

只需确保将functions视图块中的所有代码移动到基类中,因为混合这两种方法可能会产生奇怪的副作用。


推荐阅读