I use checkboxes in an MVC5 Razor View and retrieve the checkbox values from Controller successfully by using ViewBag as shown below:
Controller:
public ActionResult Create()
{
ViewBag.RolesList = new SelectList(
this.RoleManager.Roles.ToList(), "Id", "Name");
return PartialView("_Create");
}
View:
@model Identity.ApplicationGroup
@foreach (var item in (SelectList)ViewBag.RolesList)
{
<div class="checkbox">
<label>
<input type="checkbox" name="@item" value="@item.Text">
@item.Text
</label>
</div>
}
However, I cannot pass the checkbox values to the Controller via AJAX as shown below while all of the other parameters are posted without any problem. So, how can I post them as the model values?
View:
function insert(event) {
var formdata = $('#frmCreate').serialize();
$.ajax({
type: "POST",
url: '@Url.Action("Insert", "GroupsAdmin")',
cache: false,
dataType: "json",
data: formdata
});
};
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Insert([Bind(Exclude = null)] ApplicationGroup
applicationgroup, params string[] selectedRoles)
{
...
}