The main problem is string property stores single string, you should use collection property to bind with checkboxes e.g. List<string> as @Ajay mentioned before.
Therefore, you should use this setup:
Model
public class MyModel
{
public MyModel()
{
SelectedCategories = new List<string>();
// put categories here
Categories = new List<SelectListItem>() { ... };
}
// other properties
public List<string> SelectedCategories { get; set; }
public List<SelectListItem> Categories { get; set; }
}
View
@foreach (var item in Model.Categories)
{
<input type="checkbox" name="SelectedCategories" value="@item.Value" ... />
}
Controller
[HttpPost]
public ActionResult Index(MyModel model)
{
if (ModelState.IsValid)
{
// create comma-separated values
var selectedCategories = string.Join(",", model.SelectedCategories);
// Save data to database, and redirect to Success page.
return RedirectToAction("Success");
}
}
If you want to use CheckBoxFor helper, use SelectListItem which has Selected property with bool type, because CheckBoxFor binds for bool property:
Model
public class MyModel
{
public MyModel()
{
// put categories here
Categories = new List<SelectListItem>() { ... };
}
// other properties
public List<SelectListItem> Categories { get; set; }
}
View
@for (var i = 0; i < Model.Categories.Count; i++)
{
@Html.CheckBoxFor(model => model.Categories[i].Selected)
@Html.HiddenFor(model => model.Categories[i].Text)
@Html.HiddenFor(model => model.Categories[i].Value)
}
Controller
[HttpPost]
public ActionResult Index(MyModel model)
{
if (ModelState.IsValid)
{
string selectedCategories = string.Join(",",
model.Categories.Where(x => x.Selected == true)
.Select(x => x.Text).ToList());
// Save data to database, and redirect to Success page.
return RedirectToAction("Success");
}
}
Note:
There is a custom helper named CheckBoxListFor which should be considered to create checkbox list from List<T> property.
An example of the checkbox list implementation can be seen here.
Related problems:
Get comma-separated string from CheckboxList HTML Helper
Get Multiple Selected checkboxes in MVC