実装
前回のコードをこんな感じに変更します。
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using MySql.Data.MySqlClient; namespace aspdotnet_mysql_sample.Pages { public class IndexModel : PageModel { private readonly String DBName = "aspdotnet"; private readonly String DBHost = "127.0.0.1"; private readonly String DBPort = "43306"; private readonly String DBUser = "root"; private readonly String DBPass = "mysql"; private readonly String TableName = "data"; private readonly ILogger<IndexModel> _logger; private MySqlConnection connection; public string ResultText { get; set; } public IndexModel(ILogger<IndexModel> logger) { _logger = logger; String ConnectionString = $"server={DBHost};port={DBPort};uid={DBUser};pwd={DBPass};database={DBName}"; try { connection = new MySqlConnection(); connection.ConnectionString = ConnectionString; connection.Open(); Console.WriteLine(connection.ServerVersion); } catch (MySqlException e) { Console.WriteLine(e.Message); } } ~IndexModel() { connection.Close(); Console.WriteLine("Connection Closed"); } public void OnGet() { String sql = $"SELECT * FROM {TableName}"; MySqlCommand command = new MySqlCommand(sql, connection); MySqlDataReader dataReader = command.ExecuteReader(); while (dataReader.Read()) { Console.WriteLine($"{dataReader[0]} -- {dataReader[1]}"); ResultText += $"{dataReader[0]}:{dataReader[1]}{Environment.NewLine}"; } dataReader.Close(); } } }
取得したデータをResultText
に追加していくようにしただけです。
更に、Index.cshtmlを以下のように変更します。
@page @model IndexModel @{ ViewData["Title"] = "Home page"; } <div class="text-center"> <h1 class="display-4">Welcome</h1> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> @if (!String.IsNullOrEmpty(Model.ResultText)) { <pre><code>@Model.ResultText</code></pre> } </div>
ResultText
が存在すれば出力する。という感じです。
String.IsNullOrEmptyはC#のメソッドですが、クライアント側で動いているかのように記述できるのがRazorの特徴です。
RazorではWebページ出力時にはただのHTMLとして出力されますが、Blazorを使えばクライアント側でC#のコードを動かすことができます。
動作確認
前回同様にブラウザでアクセスし、以下のように表示されていればOKです。
おわりに
とりあえずDBのデータを表示できるようになりましたが、このままでは見栄えが悪いですね。
クライアント側で文字列をいじってテーブル形式にしてもいいですが、車輪の再発明感が否めません。
そこで、次回はここをいい感じにしてくれる物を使っていこうと思います。