Example:
1 - View
@model WebApplication2.Models.BaseModel
@{
ViewBag.Title = "Listas";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Listas</h2>
@using (Html.BeginForm())
{
@Html.CheckBoxListFor(
p => p.BaseSend.Send,
p => p.BaseAll,
p => p.Id,
p => p.Name,
b => b.BaseSelected
)
<button type="submit">Enviar</button>
}
2 - Classes
public class Base
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
public object Tags { get; set; }
}
public class BaseModel
{
public IEnumerable<Base> BaseAll { get; set; }
public IEnumerable<Base> BaseSelected { get; set; }
public BaseSend BaseSend { get; set; }
}
public class BaseSend
{
public string[] Send { get; set; }
}
3 - Controller () Method: Lists (GET and POST)
public ActionResult Listas()
{
BaseModel baseModel = new BaseModel();
baseModel.BaseAll = new List<Base>(){
new Base() { Id = 1, Name="Produto 1", IsSelected = true, Tags="Produtos"},
new Base() {Id = 2, Name="Produto 2", IsSelected = false, Tags="Produtos"}
};
baseModel.BaseSelected = new List<Base>(){
new Base() { Id = 1, Name="Produto 1", IsSelected = true, Tags="Produtos"},
};
return View(baseModel);
}
[HttpPost]
public ActionResult Listas(BaseSend BaseSend)
{
return RedirectToAction("Listas");
}
4 - Html Generated
5-RetrievingValues
All copyrights of the site How to Use CheckBoxListFor With ASP.NET MVC 4?