ヘッダー
C# Sample Programs
 

Trun on/off checkboxes

04/17/2024

This article deals with ASP.NET Core Razor Pages.

 

All sample programs in this article are based on the Visual Studio Project template "ASP.NET Core Web App" and you must add the Razor pages in th Pages folder.

 

 

Turn on a checkbox and turn off another checkbox

For this example, when you click a submit button, the first checkbox(Mikan) will be checked and the second checkbox(Banana) will be unchecked.

CheckBoxSetValue.cshtml.cs

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

namespace WorkStandard.Pages.controls
{
    public class CheckBoxSetValueModel : PageModel
    {
        [BindProperty]
        [DisplayName("Mikan")]
        public bool IsMikan { get; set; }

        [BindProperty]
        [DisplayName("Banana")]
        public bool IsBanana { get; set; } = true; //Set the initial value of the Banana to checked state.

        public void OnPost()
        {
            System.Diagnostics.Debug.WriteLineIf(IsMikan, "The Mikan is checked.");
            System.Diagnostics.Debug.WriteLineIf(IsBanana, "The Banana is checked.");

            //Make the Mikan checked and the Banana unchecked.
            ModelState.Remove(nameof(IsMikan));
            ModelState.Remove(nameof(IsBanana));

            IsMikan = true;
            IsBanana = false;
        }
    }
}

Where Debug.WriteLine appear

Note: Mikans are a delicious fruit of Japan. → Wikipedia

 

CheckBoxSetValue.cshtml

@page
@model WorkStandard.Pages.controls.CheckBoxSetValueModel

<form method="post">
    <div class="mb-3 form-check">
        <input asp-for="IsMikan" class="form-check-input" />
        <label asp-for="IsMikan" class="form-check-label"></label>
    </div>
    <div class="mb-3 form-check">
        <input asp-for="IsBanana" class="form-check-input" />
        <label asp-for="IsBanana" class="form-check-label"></label>
    </div>
    <div>
        <input type="submit" class="btn btn-primary" />
    </div>
</form>

The CSS classes...

  • mb-3 Set little margin at bottom.→ Spacing
  • form-check form-check-input Give the input a Bootstrap look. → Checks
  • form-check form-check-label Give the label a Bootstrap look.→ Checks
  • btn btn-primary Give the button a Bootstrap look to indicate that it's a key feature.→ Buttons

 


日本語版