0

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)
{
    ...
}
Satpal
  • 132,252
  • 13
  • 159
  • 168
Jack
  • 1
  • 21
  • 118
  • 236
  • 1
    Why in the world are you using a `SelectList`. And what is the point of passing an `Id` value when you never use it. And look at the `name` attribute of your checkboxes to understand why you code does not work. –  Dec 08 '16 at 07:42
  • 1
    Suggest you look at [this answer](http://stackoverflow.com/questions/29542107/pass-list-of-checkboxes-into-view-and-pull-out-ienumerable/29554416#29554416) for how to implement your checkboxes ao that you can use `.serialize()` to correctly post back the data –  Dec 08 '16 at 07:44
  • @StephenMuecke Thanks, I tried to follow the answer you suggested. But if it is possible, how can I solve the problem by modifying almost anything as much possible? Is it possible to fix the problem by not usinbg ViewModels (ASP.NET Identity tas already the mentioned reletion between Role and RoleGroups). Any idea? – Jack Dec 08 '16 at 08:54
  • 1
    In the controller (since you seem to want only the role names) - `ViewBag.RolesList = RoleManager.Roles.Select(x => x.Name);` And in the view `@foreach (string role in ViewBag.RolesList) { }` –  Dec 08 '16 at 08:59
  • @StephenMuecke Perfect!.. Thanks a lot Stephen :) – Jack Dec 09 '16 at 08:38

0 Answers0