[.NET MVC]如何存取checkboxlist

  • 2341
  • 0
  • 2019-08-13

[.NET MVC]如何存取checkboxlist

Model:

public class UsersSearchModel
{
	public string EmployeeID { get; set; }
	public string Name { get; set; }
	public string Unit { get; set; }
	
	//控制畫面上群組的checkboxlist
	public List<string> SelectedGroups { get; set; }//畫面上checkboxlist選擇的群組
	public List<SelectListItem> AvailableGroups { get; set; }//所有可用的checkboxlist群組

	public UsersSearchModel()
	{
		//記得初始化
		SelectedGroups = new List<string>();
		AvailableGroups = new List<SelectListItem>();
	}

}


controller:

public ActionResult Index()
{	
	UsersSearchModel searchVM = new UsersSearchViewModel();	
	//使用者群組checkboxlist	
	searchVM.AvailableGroups = GetCheckboxListItems();
	
	
	return View(searchVM);
}

//通常取得checkboxlist的動作都是在dal層面去完成
//這邊為了方便,直接寫在controller
private List<SelectListItem> GetCheckboxListItems()
{
	return new List<SelectListItem>
	{
		new SelectListItem {Text = "groupname1", Value = "group1"},
		new SelectListItem {Text = "groupname2", Value = "group2"},
		new SelectListItem {Text = "groupname3", Value = "group3"},
		new SelectListItem {Text = "groupname4", Value = "group4"},
	};
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(UsersSearchModel model)
{	
	//使用者打勾的使用者群組checkboxlist	
	string[] myArray = model.SelectedGroups.ToArray()
	
	return View();
}


View:
AvailableGroups是用來顯示所有的checkboxlist用的
SelectedGroups是用來顯示你剛剛打勾了哪些checkboxlist用的

<div class="form-group">
	<div class="row ">
		@Html.Label("your label name", htmlAttributes: new { @class = "control-label col-md-2" })
		<div class="col-md-10">
			@{

				foreach (var item in Model.AvailableGroups)
				{
					<input type="checkbox" value="@item.Value" name="SelectedGroups"
						   @{ if (Model.SelectedGroups.Contains(item.Value)) { <text> checked </text>  } }
						   id="@item.Text" class="custom-control-input" />

					<label class="custom-control-label" for="@item.Text">@item.Text</label>

				}
			}

		</div>
	</div>

</div>




參考資料:
How to make Check Box List in ASP.Net MVC
https://stackoverflow.com/questions/37778489/how-to-make-check-box-list-in-asp-net-mvc