- 首先替checkbox建立一個model
public class RoleCheckBoxModel
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
public bool Checked
{
get;
set;
}
}
|
- 在HomeController 中建立一個 Action 並且宣告一個List來放我們的 RoleCheckBoxModel 然後再傳給 view
public ActionResult AddRole()
{
var list = new List<RoleCheckBoxModel>
{
new RoleCheckBoxModel{Id = 1, Name = "Admin", Checked = false},
new RoleCheckBoxModel{Id = 2, Name = "Guest", Checked = false},
new RoleCheckBoxModel{Id = 3, Name = "Member", Checked = false},
};
return View(list);
}
|
- 建立一個view(在action裡面按右鍵,並選擇 add view)
- 把 List<RoleCheckBoxModel> 帶到 view 裡面之後,透過 @Html.CheckBoxFor 來建立checkbox
@model List<TestForCreateCheckBoxInMVC.Models.RoleCheckBoxModel>
@using (Html.BeginForm())
{
for (var i = 0; i < Model.Count(); i++)
{
<table>
<tr>
<td>
@Html.DisplayFor(it => it[i].Name)
</td>
<td>
@Html.CheckBoxFor(it => it[i].Checked, new { Style = "vertical-align:3px}" })
</td>
</tr>
</table>
}
@Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
|
- 加入一個post action方法來取得並處理view傳過來的資料
[HttpPost]
public ActionResult AddRole(List<RoleCheckBoxModel> list)
{
foreach (var item in list)
{
if (item.Checked)
{
//Do something
}
}
return View();
}
|
完整Sample cde:
https://github.com/andy51002000/SimpleASPMVCCheckbox.git
留言
張貼留言