.net8 blazor auto模式很爽(四)改造vs自动创建的Blazor auto为前后端分离模式(1)

发布于:2024-06-21 ⋅ 阅读:(93) ⋅ 点赞:(0)

        我们在“解决方案BlazorApp1”右键添加项目,选择“类库”,点击下一步:

将项目名称改为“SharedLibrary”,用来存放前后端共享的一些类和接口。下面我们把SharedLibrary设置为前后端的共同依赖。双击“BlazorApp1”和BlazorApp1.Client,出现配置文件,在里面增加“<ItemGroup>
    <ProjectReference Include="..\..\SharedLibrary\SharedLibrary.csproj" />
</ItemGroup>”。在SharedLibrary新建一个文件夹“Models”用来存放一些实体类。我们在Models新建一个类,叫WeatherForecast:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SharedLibrary.Models
{
    public class WeatherForecast
    {
        public DateTime Date { get; set; }
        public int TemperatureC { get; set; }
        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
        public string? Summary { get; set; }
    }
}

在Client的pages中新建:Weather.razor:

@page "/weather"
 @rendermode InteractiveAuto


<PageTitle>Weather</PageTitle>

<h1>Weather</h1>

<p>This component demonstrates showing data.</p>

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Date</th>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in forecasts)
            {
                <tr>
                    <td>@forecast.Date.ToShortDateString()</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    private List< WeatherForecast>? forecasts;

    protected override async Task OnInitializedAsync()
    {
        // Simulate asynchronous loading to demonstrate streaming rendering
        await Task.Delay(500);
        forecasts = await WeatherForecastServices.GetWeatherForecastAsync();
        
       
    }

    
}

删除掉BlazorApp1的Weather.razor