如何在ASP.Net MVC中制作复选框列表

我有一个带有复选框列表的表单。 用户可以选择所有值,没有值或其间的任何值。 例:

目标的截图

我想以逗号分隔列表的forms将结果写入数据库。 在上面的例子中,“Apple,Banana”。 我有点困惑如何为此创建模型以及如何将View中的结果转换为逗号分隔列表?

这是一个如何做到这一点的例子。

HomeModel.cs

public class HomeModel { public IList SelectedFruits { get; set; } public IList AvailableFruits { get; set; } public HomeModel() { SelectedFruits = new List(); AvailableFruits = new List(); } } 

HomeController.cs

 public class HomeController : Controller { public ActionResult Index() { var model = new HomeModel { AvailableFruits = GetFruits() }; return View(model); } [HttpPost] public ActionResult Index(HomeModel model) { if (ModelState.IsValid) { var fruits = string.Join(",", model.SelectedFruits); // Save data to database, and redirect to Success page. return RedirectToAction("Success"); } model.AvailableFruits = GetFruits(); return View(model); } public ActionResult Success() { return View(); } private IList GetFruits() { return new List { new SelectListItem {Text = "Apple", Value = "Apple"}, new SelectListItem {Text = "Pear", Value = "Pear"}, new SelectListItem {Text = "Banana", Value = "Banana"}, new SelectListItem {Text = "Orange", Value = "Orange"}, }; } } 

Index.cshtml

 @model DemoMvc.Models.HomeModel @{ Layout = null; }     Index    
@using (Html.BeginForm("Index", "Home")) { foreach (var item in Model.AvailableFruits) {
}
}

哪个应该在Post Action中产生以下结果:

发布行动

您也可以使用jquery.No需要更改任何控制器或操作。它只是将选中的复选框值添加到数据库表的列中作为逗号分隔。只需在视图页面中添加代码。

  
@Html.HiddenFor(model => model.hobbies, new { htmlAttributes = new { id = "hobbies" } }) Hobbies : Reading Writing @Html.ValidationMessageFor(model => model.hobbies)