ヘッダー
C# サンプル集
 

トグルスイッチ

2024/5/3

この記事は ASP.NET Core Razor Pages を対象にしています。

 

この記事内のサンプルは、プロジェクトテンプレート「ASP.NET Core Web アプリ」を使用して、PagesフォルダーにこのRazorページを追加する前提です。

 

 

トグルスイッチ

ToggleSwitch.cshtml.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel;

namespace WorkStandard.Pages.controls
{
    public class ToggleSwitchModel : PageModel
    {
        [BindProperty]
        [DisplayName("自動ログオン")]
        public bool IsAutoLogon { get; set; }

        [BindProperty]
        [DisplayName("ログオン状況を公開")]
        public bool IsShareLogonStatus { get; set; } = true;

        public void OnPost()
        {
            System.Diagnostics.Debug.WriteLine($"自動ログオンは {IsAutoLogon}");
            System.Diagnostics.Debug.WriteLine($"ログオン状況を公開は {IsShareLogonStatus}");
        }
    }
}

Debug.WriteLineが表示される場所

 

ToggleSwitch.cshtml

@page
@model WorkStandard.Pages.controls.ToggleSwitchModel

<form method="post">
    <div class="mb-3 form-check form-switch">
        <input asp-for="IsAutoLogon" class="form-check-input" role="switch" />
        <label asp-for="IsAutoLogon" class="form-check-label"></label>
    </div>
    <div class="mb-3 form-check form-switch">
        <input asp-for="IsShareLogonStatus" class="form-check-input" role="switch" />
        <label asp-for="IsShareLogonStatus" class="form-check-label"></label>
    </div>
    <div>
        <input type="submit" class="btn btn-primary" />
    </div>
</form>

主なCSSクラスの効果

  • mb-3 下に少し余白(margin)を設けます。→ 余白
  • form-check form-switch form-check-input inputをBootstrapのトグルスイッチの外観にします。→ トグルスイッチ
  • form-check form-switch form-check-label labelをBootstrapのトグルスイッチのラベルの外観にします。→ トグルスイッチ
  • btn btn-primary ボタンをBootstrapの外観にして、主要な機能であることを示します。→ ボタン

 


English