- ビューモデル側
- ビューモデルに受け取り用にプロパティを配列で定義
- ビュー側
- 要素の
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^*)