如何在asp.net MVC中创建checkboxList,然后使用checkboxList
处理事件答案 0 :(得分:64)
你可以有一个视图模型:
public class MyViewModel
{
public int Id { get; set; }
public bool IsChecked { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new[]
{
new MyViewModel { Id = 1, IsChecked = false },
new MyViewModel { Id = 2, IsChecked = true },
new MyViewModel { Id = 3, IsChecked = false },
};
return View(model);
}
[HttpPost]
public ActionResult Index(IEnumerable<MyViewModel> model)
{
// TODO: Handle the user selection here
...
}
}
视图(~/Views/Home/Index.cshtml
):
@model IEnumerable<AppName.Models.MyViewModel>
@{
ViewBag.Title = "Home Page";
}
@using (Html.BeginForm())
{
@Html.EditorForModel()
<input type="submit" value="OK" />
}
和相应的编辑器模板(~/Views/Home/EditorTemplates/MyViewModel.cshtml
):
@model AppName.Models.MyViewModel
@Html.HiddenFor(x => x.Id)
@Html.CheckBoxFor(x => x.IsChecked)
现在,当您提交表单时,您将获得一个值列表以及每个值是否被选中。
答案 1 :(得分:19)
甚至更简单的方法 - 从这里使用自定义@ Html.CheckBoxList()扩展: http://www.codeproject.com/KB/user-controls/MvcCheckBoxList_Extension.aspx
用法示例(使用Razor视图引擎的MVC3视图):
@Html.CheckBoxList("NAME", // NAME of checkbox list
x => x.DataList, // data source (list of 'DataList' in this case)
x => x.Id, // field from data source to be used for checkbox VALUE
x => x.Name, // field from data source to be used for checkbox TEXT
x => x.DataListChecked // selected data (list of selected 'DataList' in thiscase),
// must be of same data type as source data or set to 'NULL'
)