1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【ASP.NET Core】動的に生成されるチェックボックスの値を取得【C#】

Posted at
  • ビューモデル側
    • ビューモデルに受け取り用にプロパティを配列で定義
  • ビュー側
    • 要素のnameに受け取り用にプロパティの変数名を設定
  • コントローラ側
    • ビューモデルを引数に取るアクションを定義
ビューモデル
namespace Test
{
    public class ViewModel
    {
        /// <summary>
        /// 選択された値を取得します。
        /// </summary>
        public string[] SelectedValues { get; set; }
    }
}
ビュー
@model Test.ViewModel

@{
    ViewData["Title"] = "ページタイトル";
}
<div>
    <h1>@ViewData["Title"]</h1>
    <form asp-controller="Test" asp-action="Index" method="post">
        <ul>
            <li>
                <label for="id1"></label>
                <input id="id1" type="checkbox" name="SelectedValues" />
            </li>
            <li>
                <label for="id2"></label>
                <input id="id2" type="checkbox" name="SelectedValues" />
            </li>
            <li>
                <label for="id3"></label>
                <input id="id3" type="checkbox" name="SelectedValues" />
            </li>
            <li>
                <label for="id4"></label>
                <input id="id4" type="checkbox" name="SelectedValues" />
            </li>
            <li>
                <label for="id5"></label>
                <input id="id5" type="checkbox" name="SelectedValues" />
            </li>
        </ul>
    </form>
    <input type="submit" value="送信" />
</div>
コントローラ
using Microsoft.AspNetCore.Mvc;

namespace Test
{
    public class TestController : Controller
    {
        [HttpPost]
        public ActionResult Index(ViewModel model) => this.View(model);
    }
}

それだけ(*^o^*)

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?