close

因為 .Net5 的推出,正式宣佈了Blazor˙來臨,

相關的技術請參考微軟的技術文件,還有很多的文章,

我自己也會慢慢寫出來,

我這邊只解釋一下資料實作,

首先你必須要知道Blazor都是在前端運行,

這一點回到了以前CodeBeside了,

除了Razor還有很多結合以前WebForm或是很多前端工程的template之類的,

這篇不解釋這個,

我只解釋資料怎麼來,

首先

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
@code {
    private List<WeatherForecast> forecasts;

    protected override async Task OnInitializedAsync()
    {
        forecasts = await Http.GetFromJsonAsync<List<WeatherForecast>>("sample-data/weather.json");
    }

    public class WeatherForecast
    {
        public DateTime Date { get; set; }

        public int TemperatureC { get; set; }

        public string Summary { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    }
}

 

我們知道這是C#,這是預設的VS 2019 Blazor專案,你開啟就可以跑了.

首先我們用我們習慣的方式把WeatherForecast從預設的陣列改成習慣的List<T>

這樣比較好懂一點,

async Task OnInitializedAsync()

就是程式進入點

我們在Blazor開頭注入了@inject HttpClient Http

於是使用了 Http.GetFromJsonAsync<T>(); 來取得Json

並將之反序列化,到定義的Model public class WeatherForecast

這樣就有 private List<WeatherForecast> forecasts;

目前為止都不難

以下更簡單

我們開始來組織頁面

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@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>
}

 

因為是非同步處理,要先確保有沒有資料,沒有資料先顯示lLoading...

一有資料進來,就開始處理資料內容,

這不是Ajax!! 

這是WebAssembly!!

 

arrow
arrow
    文章標籤
    asp.net Blazor .NET 5
    全站熱搜
    創作者介紹
    創作者 baechang 的頭像
    baechang

    翁百璋與大泡泡的奇幻旅程

    baechang 發表在 痞客邦 留言(0) 人氣()