-1

I am working on this website and I'm having difficulties on setting a true or false from my check box to the database to set my IsActive value to true or false to update an account am using code first approach on MVC.

on my Account and identity models

public class RegisterViewModel { public bool IsActive { get; set; } }

and on my account controller

  //
    // GET: /Account/Update
    [HttpGet]
    [ETAuthorizeAttribute]
    public ActionResult Update(string email)
    {
        var user = _db.Users.FirstOrDefault(x => x.Email == email);
       ViewBag.IsActive = user.IsActive;
        ViewBag.CostCentres = new SelectList(_db.CostCentres.Select(x => x.Station).Distinct());
        ViewBag.Hotel = new SelectList(_db.Hotels.Where(x => x.IsBlocked == true).Distinct(), "HotelId", "HotelName");
        string selected = "";
        foreach (var item in user.Roles)
            selected += item.RoleId + ",";
        ViewBag.Selected = selected;
        ViewBag.Roles = _db.Roles.ToList();

        RegisterViewModel model = new RegisterViewModel();
        model.Email = user.Email;
        return View(model);
    }

    //
    // POST: /Account/Register
    [HttpPost]
    [ETAuthorizeAttribute]
    [ValidateAntiForgeryToken]
    public ActionResult Update(RegisterViewModel model)
    {

        bool isActive = Convert.ToBoolean(Request.Form["active"]);
        string role = Request.Form["role"];
        if (role != null)
        {

            ApplicationUser user = _db.Users.FirstOrDefault(x => x.Email == model.Email);
            if (user != null)
            {
                user.HotelId = model.HotelId;
                user.Station = model.Station;
                user.FullName = model.FullName;
                 user.IsActive = isActive;

                try { 

                _db.Entry(user).State = EntityState.Modified;
                _db.SaveChanges();
                }
            //  return RedirectToAction("Index");

                catch(Exception e)
                { 
                _db.ClearUserRoles(UserManager, user.Id);
                string[] roles = role.Split(',');
                foreach (var item in roles)
                {
                    string name = _db.Roles.FirstOrDefault(x => x.Id == item).Name;
                    _db.AddUserToRole(UserManager, user.Id, name);
                }
                return RedirectToAction("Index", "Account");
            }
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

and on my view ...

  <div class="form-group">
         @Html.Label("IsActive", new { @class = "control-labelcol-md-2" })
               <div class="col-md-10">
        <div class="checkbox col-md-3">
 @if (ViewBag.IsActive)
 { 
 <input type="checkbox" name="active" value="@ViewBag.IsActive" checked/>}
    else
           {
 <input type="checkbox" name="active" value="@ViewBag.IsActive"  /> }
                            </div>

                    </div>
                </div>
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
ILoveCode
  • 235
  • 2
  • 3
  • 11

2 Answers2

2

Basically you must have your name of your HTML control the same as the variable in your controller example:

public ActionResult Index(bool checkboxControl)
{
   return View();
}

and in your HTML side the code must be

<input type="checkbox" name="checkboxControl" />

It doesn't matter if you are using a code first approach or DB first, this is the fundamental way MVC works

BroCode
  • 21
  • 3
  • i think I've done that but i keep encountering errors saying "validation error" – ILoveCode Aug 22 '16 at 08:33
  • Try running your code get the html controller and see what that controllers name is... if the name is right and your controllers parameter is the same name... than the problem doesn't lie with the physical passing of the value from html to controller.... Also check if you get the "validation error" if you make the parameter nullable so in your controller method just make it bool with a question mark behind it example: bool? – BroCode Aug 22 '16 at 08:39
  • The error says "string entity is not a valid boolean" – ILoveCode Aug 22 '16 at 08:42
  • you should get the value that you are passing into your inputs that @Viewbag.IsActive – BroCode Aug 22 '16 at 08:46
  • ok wait if i understand correctly you just want to make one checkbox and it should change the IsActive property in your model accordingly? if you want to achieve this just use razors @Html.CheckBoxFor just read up on it... basicly it wil generate a input like my html and make the name the models name – BroCode Aug 22 '16 at 08:51
  • I want to make a check box that updates the database to true value when Its checked and to false when its not... all am trying to accomplish is updating ones account – ILoveCode Aug 22 '16 at 09:03
  • use Nauman Khan 's answer and change your controller instead of public ActionResult Update(RegisterViewModel model) to public ActionResult Update(bool IsActive) – BroCode Aug 22 '16 at 11:13
0

You are not passing value of check box in model

<div class="form-group">
     @Html.Label("IsActive", new { @class = "control-labelcol-md-2" })
     <div class="col-md-10">
        <div class="checkbox col-md-3">
             @if (ViewBag.IsActive)
                   { 
                     <input type="checkbox" name="active" value="@ViewBag.IsActive" checked/>
                   } else
                        {
                          <input type="checkbox" name="active"     value="@ViewBag.IsActive"  /> }
         </div>

      </div>
</div>

change this to

    <div class="form-group">
             @Html.Label("IsActive", new { @class = "control-labelcol-md-2})
                <div class="col-md-10">
                    <div class="checkbox col-md-3">
                    @Html.CheckBoxFor(m => m.IsActive, new { id = "YourId"})
                    </div>
                </div>
     </div>

You need to check in view it will work according to value you are passing from server side..

Hopefully it will work for you ..

Nauman Khan
  • 509
  • 7
  • 20
  • bool active= Convert.ToBoolean(Request.Form["myID"]);... is this conversion correct – ILoveCode Aug 22 '16 at 10:39
  • You said you model is like 'public class RegisterViewModel { public bool IsActive { get; set; } }' so if you this feild in database is string then you just check by **If ** Condition that is Isactive is true send some string database ... this can easily done in server side but if you database have bit type datatype then no need of any conversion. – Nauman Khan Aug 22 '16 at 11:41