jeudi 17 septembre 2015

MVC how to save checkboxes to db

I have been searching for some articles which whould help me, but no success. So I have table for users and table for roles for user in db. I already have method that shows me roles and checkboxes for each. The ones the user have are checked, but I also need method that will save checked roles in view, I hope you will get it from my code.

Controller

public ActionResult Role( int id)
    {


        UsersRole u = _context.UsersRoles.Find(id);
        UserRoleModel model = new UserRoleModel();


       // var test = _context.UsersRoles.Select(c => new RoleVM { Name = c.Role, ID = c.ID }).GroupBy(g=> g.Name).ToList();
        Dictionary<int, string> seznamroli = new Dictionary<int, string>();
        seznamroli.Add(1, "Administrator");
        seznamroli.Add(2, "Gestor");
        seznamroli.Add(3, "Supervisor");
        seznamroli.Add(4, "SecurityManager");
        seznamroli.Add(5, "Admin");



        model.ListRole = seznamroli.Select(c => new RoleVM
        { 
            Name = c.Value,
            IsSelected = _context.UsersRoles.Any(m => (m.UserID == id && c.Value == m.Role))

        }).ToList();

        return View(model);



    }

Model

 public class UserRoleModel
{
        public int ID { get; set; }     
        public int? UserID { get; set; }
        public UserRoleModel()
         {
             ListRole = new List<RoleVM>();
         }
        public string Name { get; set; }
        public List<RoleVM> ListRole { get; set; }
        public List<RoleVM> UserRole { get; set; }
}

public class RoleVM

{
    public int ID { get; set; }
    public string Name { get; set; }
    public bool IsSelected { get; set; }
}

The View

                                          @for (int i = 0; i < Model.ListRole.Count; i++)
                                          {
                                                  @Html.HiddenFor(m => m.ListRole[i].ID)
                                                  @Html.CheckBoxFor(m => m.ListRole[i].IsSelected, new { @checked = "checked" });
                                                  @Html.LabelFor(m => m.ListRole[i].IsSelected, Model.ListRole[i].Name)
                                              <br/>                                              
                                          }
                                        </div>
                                    </div>                                      
                                </div>


                                <div class="form-group">
                                    <div class="col-md-offset-2 col-md-10">
                                        <button type="submit" class="btn btn-primary">@ARAMIS.Resources.ARAMIS.User_Edit_Save</button>
                                    </div>




Aucun commentaire:

Enregistrer un commentaire