I did had a problem with the most of solutions, since I was trying to use a checkbox with a specific style. I was in need of the values of the checkbox to send them to post from a list, once the values were collected, needed to save it. I did manage to work it around after a while.
Hope it helps someone. Here's the code below:
Controller:
[HttpGet]
public ActionResult Index(List<Model> ItemsModelList)
{
ItemsModelList = new List<Model>()
{
//example two values
//checkbox 1
new Model{ CheckBoxValue = true},
//checkbox 2
new Model{ CheckBoxValue = false}
};
return View(new ModelLists
{
List = ItemsModelList
});
}
[HttpPost]
public ActionResult Index(ModelLists ModelLists)
{
//Use a break point here to watch values
//Code... (save for example)
return RedirectToAction("Index", "Home");
}
Model 1:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace waCheckBoxWithModel.Models
{
public class Model
{
public bool CheckBoxValue { get; set; }
}
}
Model 2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace waCheckBoxWithModel.Models
{
public class ModelLists
{
public List<Model> List { get; set; }
}
}
View (Index):
@{
ViewBag.Title = "Index";
@model waCheckBoxWithModel.Models.ModelLists
}
<style>
.checkBox {
display: block;
position: relative;
margin-bottom: 12px;
cursor: pointer;
font-size: 22px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* hide default checkbox*/
.checkBox input {
position: absolute;
opacity: 0;
cursor: pointer;
}
/* checkmark */
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 25px;
width: 25px;
background: #fff;
border-radius: 4px;
border-width: 1px;
box-shadow: inset 0px 0px 10px #ccc;
}
/* On mouse-over change backgroundcolor */
.checkBox:hover input ~ .checkmark {
/*background-color: #ccc;*/
}
/* background effect */
.checkBox input:checked ~ .checkmark {
background-color: #fff;
}
/* checkmark (hide when not checked) */
.checkmark:after {
content: "";
position: absolute;
display: none;
}
/* show checkmark (checked) */
.checkBox input:checked ~ .checkmark:after {
display: block;
}
/* Style checkmark */
.checkBox .checkmark:after {
left: 9px;
top: 7px;
width: 5px;
height: 10px;
border: solid #1F4788;
border-width: 0 2px 2px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
</style>
@using (Html.BeginForm())
{
<div>
@{
int cnt = Model.List.Count;
int i = 0;
}
@foreach (var item in Model.List)
{
{
if (cnt >= 1)
{ cnt--; }
}
@Html.Label("Example" + " " + (i + 1))
<br />
<label class="checkBox">
@Html.CheckBoxFor(m => Model.List[i].CheckBoxValue)
<span class="checkmark"></span>
</label>
{ i++;}
<br />
}
<br />
<input type="submit" value="Go to Post Index" />
</div>
}