コードビハインド的な書き方
- ロジック部分を別ファイル、別クラスに記述しておく。
- そのクラスは
ComponentBase
クラスを継承しておく。
- Razorファイルから利用するプロパティやメソッドは
public
にしておく。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
namespace Blazor.ViewModels
{
public class IndexViewModel : ComponentBase
{
public string greeting { get; set; } = "Hello, world!";
public string currentDateTime { get; set; } = "???";
public void GetDateTime()
{
this.currentDateTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
}
}
}
- Razorファイル側ではそのクラスへの参照を記述する。
@inherits
ディレクティブを使って。
@page "/"
@inherits Blazor.ViewModels.IndexViewModel
<h1>@greeting</h1>
Welcome to your new app.
@*<SurveyPrompt Title="How is Blazor working for you?" />*@
<Counter IncrementAmount="10" />
<FetchData />
<button class="btn btn-primary" onclick="@GetDateTime">Get Current Time</button>
<label>@currentDateTime</label>