如何在Blazor.Net中将代码与UI分开 [英] How to Separate Code From UI In Blazor.Net

查看:256
本文介绍了如何在Blazor.Net中将代码与UI分开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对此VisualStudioMagazine 文章,我试图将代码保存在单独的文件中,而不是剃刀视图中.

Reference to this VisualStudioMagazine article, I am trying to have code in a separate file instead of razor view.

我尝试过:

@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();
    }
}

和ItemComponent:

And ItemComponent:

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;
        }

    }
}

但是它不起作用,它表明:

But it does not work , it shows that:

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

Severity Code Description Project File Line Suppression State Error CS0115 'Item.BuildRenderTree(RenderTreeBuilder)': no suitable method found to override WebApplication1.Client D:\Other\blazor\WebApplication1.Client\obj\Debug\netstandard2.0\RazorDeclaration\Pages\ItemModule\Item.razor.g.cs 30 Active

根据教程页面,也不能继承BlazorComponentItemComponent,因为它没有引用.

Also as per tutorial page can not inherit BlazorComponent to ItemComponent because it failed to have reference.

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

Is there any way to separate most of the code from Blazor view to a separate code file?

更新1

按照Chris Answers进行更改后,它会显示异常

After Making changes as per Chris Answer, it show exception

System.Net.Http.HttpRequestException:无法建立连接,因为目标计算机主动拒绝了它. ---> System.Net.Sockets.SocketException:无法建立连接 因为目标计算机主动拒绝了它.在 System.Net.Http.ConnectHelper.ConnectAsync(字符串主机,Int32端口, CancellationToken cancellingToken)-内部异常结束 堆栈跟踪--- System.Net.Http.ConnectHelper.ConnectAsync(字符串主机,Int32端口, 的CancellationToken cancelToken() System.Threading.Tasks.ValueTask 1.get_Result() at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask
1.get_Result()在 System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage 请求,请在以下位置输入CancellationToken cancelToken) System.Threading.Tasks.ValueTask 1.get_Result() at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask 1.get_Result()在 System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request,布尔值doRequestAuth,CancellationToken cancelledToken)
在System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage 请求,请在以下位置输入CancellationToken cancelToken) System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(任务1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at System.Net.Http.HttpClient.GetStringAsyncCore(Task 1 getTask) Microsoft.AspNetCore.Builder.BlazorMonoDebugProxyAppBuilderExtensions.GetOpenedBrowserTabs(String debuggerHost)在 Microsoft.AspNetCore.Builder.BlazorMonoDebugProxyAppBuilderExtensions.DebugHome(HttpContext 上下文)

System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it. ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it. at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken) at 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.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at System.Net.Http.HttpClient.GetStringAsyncCore(Task1 getTask) at Microsoft.AspNetCore.Builder.BlazorMonoDebugProxyAppBuilderExtensions.GetOpenedBrowserTabs(String debuggerHost) at Microsoft.AspNetCore.Builder.BlazorMonoDebugProxyAppBuilderExtensions.DebugHome(HttpContext context)

推荐答案

您只需要像这样从ItemComponent类中的ComponentBase继承.

You just need to inherit from ComponentBase in your ItemComponent class like this.

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在不久前被重命名了.

The article is a little out of date as BlazorComponent was renamed a while ago.

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

Just make sure to move all of the code you have in the functions block of your view into the base class as mixing the two approaches can have odd side effects.

这篇关于如何在Blazor.Net中将代码与UI分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆