friedX
friedX

Reputation: 327

How to repopulate checkbox from boolean model property in MVC3 view

I have two Edit User Action methods. The first populates a checkbox correctly with the IsAdmin property.

public ActionResult Edit(string username)
{
    var user = Membership.GetUser(username);
    var model = Map(user);
    return View(model);
}

The second method should check if the logged in user has tried to delete their own admin privs (unchecked the checkbox) and repopulate the checkbox by setting the model.IsAdmin property back to true. The returned model is correctly populated but the checkbox does not get checked.

    [HttpPost]
    public ActionResult Edit(UserModel model)
    {
        if (model.UserName == User.Identity.Name && model.IsAdmin == false)
        {
            ModelState.AddModelError("", "You cannot remove your own admin privileges");
            model.IsAdmin = true;
            return View(model);
        }

        if (ModelState.IsValid)
        {
            //...
        }
    }

The Edit User view looks like this

<div class="simpleform">
@using (Html.BeginForm())
{
    <fieldset>
        <div>
            @Html.LabelFor(u => u.UserName)</div>
        <div>
            @Html.TextBoxFor(u => u.UserName)</div>
        <div>
            @Html.LabelFor(u => u.IsAdmin)</div>
        <div>

            @Html.CheckBoxFor(u => u.IsAdmin)</div>
        <br />
        <div>
            <input type="submit" value="Submit" />
            @Html.ActionLink("Cancel", "Index")</div>
    </fieldset>
}

Upvotes: 1

Views: 526

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039238

Remove the value from modelstate before trying to modify it, otherwise the CheckBoxFor helper will use the value from modelstate instead of the one in the view model:

if (model.UserName == User.Identity.Name && model.IsAdmin == false)
{
    ModelState.AddModelError("", "You cannot remove your own admin privileges");
    ModelState.Remove("IsAdmin");
    model.IsAdmin = true;
    return View(model);
}

Upvotes: 1

Related Questions