jeudi 14 janvier 2016

Checked CheckBox not showing up in ActionResult FormsCollection MVC 6

In the my View to add Role To User my checkboxes show all the Roles available:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    @Html.HiddenFor(model => model.Id)
    @Html.HiddenFor(model => model.Email)
    <h3>Username:</h3>
    <div class="form-control">
        @Model.Email
    </div>

<h3>Roles:</h3>

if (roles.Any())
{
    <div >
        @foreach (var role in roles)
        {
            <input type="checkbox" name="checkRole" value="@role.Name" />


            @*@Html.CheckBox(role.Name, Model.Roles.Select(u => u.RoleId).Contains(role.Id))*@
            @Html.Label(role.Name)
            <br/>
        }
    </div>
    <br />
    <button type="submit" class="btn btn-default">Save</button>
}

The Controller that adds a role to the user works with a hard-coded value ("dev"). I would like to get the value from the FormCollection that should be passed in. Yet, in break mode, FormCollection is null when I hover over it or try to get something in the Immediate window. I know there is some complexity to check-boxes especially if not checked, yet I definitely check a box.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(ApplicationUser applicationUser, FormCollection formCollection)
{

    try
    {
        var user = context.Users.FirstOrDefault(u => u.Id == applicationUser.Id);

        await RoleAddToUser(user.Id, "dev");

    }
    catch (Exception ex)
    {
        return View(ex.StackTrace);

    }

    return RedirectToAction("Index");
}

I would think something would be sent in the Request of the Form. Does anyone see anything I've missed?




Aucun commentaire:

Enregistrer un commentaire