public ActionResult Account(CreateAccountModel model) { if (ModelState.IsValid) { using (var db = new Entities()) { var data = db.asp_User.FirstOrDefault(x => x.account == model.account); if (data == null) { //check mat khau if (string.IsNullOrEmpty(model.password)) { TempData["mess"] = "Bạn chưa nhập mật khẩu"; return RedirectToAction("ListAccount", new { id = model.account }); } data = new asp_User { account = model.account, userName = model.name, password = CoreFunction.GetMd5Hash(model.password), email = model.email }; foreach (var item in model.groups) { if (item.check && !data.asp_Group.Any(x => x.id == item.id)) { var groupItem = db.asp_Group.FirstOrDefault(x => x.id == item.id); if (groupItem != null) { data.asp_Group.Add(groupItem); } } else if (!item.check && data.asp_Group.Any(x => x.id == item.id)) { var groupItem = db.asp_Group.FirstOrDefault(x => x.id == item.id); if (groupItem != null) { data.asp_Group.Remove(groupItem); } } } db.asp_User.Add(data); db.SaveChanges(); TempData["mess"] = "Đã thêm dữ liệu thành công"; } else if (model.edit) { data.userName = model.name; if (!string.IsNullOrEmpty(model.password)) { data.password = CoreFunction.GetMd5Hash(model.password); } data.email = model.email; foreach (var item in model.groups) { if (item.check && !data.asp_Group.Any(x => x.id == item.id)) { var groupItem = db.asp_Group.FirstOrDefault(x => x.id == item.id); if (groupItem != null) { data.asp_Group.Add(groupItem); } } else if (!item.check && data.asp_Group.Any(x => x.id == item.id)) { var groupItem = db.asp_Group.FirstOrDefault(x => x.id == item.id); if (groupItem != null) { data.asp_Group.Remove(groupItem); } } } db.SaveChanges(); TempData["mess"] = "Đã cập nhật dữ liệu thành công"; } else { TempData["mess"] = "Tài khoản đã tồn tại"; } } } return RedirectToAction("ListAccount", new { id = model.account }); }
public ActionResult Account(string id) { using (var db = new Entities()) { var model = new CreateAccountModel(); model.groups = db.asp_Group.Select(x => new GroupData { id = x.id, name = x.name, description = x.description }).ToList(); var data = db.asp_User.FirstOrDefault(x => x.account == id); if (data != null) { model.account = data.account; model.name = data.userName; //model.password model.email = data.email; model.edit = true; foreach (var item in model.groups) { if (data.asp_Group.Any(x => x.id == item.id)) { item.check = true; } } } return PartialView(model); } }