コード例 #1
0
        public ResultViewModel <DepartmentEditViewModel> Post(DepartmentEditViewModel model)
        {
            ResultViewModel <DepartmentEditViewModel> result
                = new ResultViewModel <DepartmentEditViewModel>();

            try
            {
                if (!ModelState.IsValid)
                {
                    result.Message = "In Valid Model State";
                }
                else
                {
                    DepartmentEditViewModel selectedUser
                        = DepartmentService.Add(model);
                    result.Successed = true;
                    result.Data      = selectedUser;
                }
            }
            catch (Exception ex)
            {
                result.Successed = false;
                result.Message   = "حدث خطأ ما";
            }
            return(result);
        }
コード例 #2
0
        public async Task <JsonResult> ContextUpdate([Bind(Include = "Key, Name")] DepartmentEditViewModel Department)
        {
            try
            {
                var Dep = await db.Departments.Include(x => x.Division.Plant.Organization).Where(x => x.Key == Department.Key).SingleOrDefaultAsync();

                Dep.Name = Department.Name;

                if (Dep == null)
                {
                    return(await JsonErrorViewModel.GetResourceNotFoundError(Response).toJson());
                }

                db.Entry(Dep).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(Json(new JDepartment(Dep), JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                return(Json(new JsonErrorViewModel {
                    Message = ex.Message
                }, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #3
0
        //[Authorize(Policy = "EditRolePolicy")]
        public async Task <IActionResult> Edit(string Id)
        {
            int decryptedId;
            int y;

            if (int.TryParse(Id, out y))
            {
                decryptedId = y;
            }
            else
            {
                decryptedId = Convert.ToInt32(protector.Unprotect(Id));
            }

            if (decryptedId < 1)
            {
                return(RedirectToAction("Index"));
            }

            Department department = await departmentService.GetDepartment(decryptedId);

            DepartmentEditViewModel model = new DepartmentEditViewModel
            {
                Id   = Id,
                Name = department.Name,
                DepartmentEncryptedId = Id
            };

            return(View(model));
        }
コード例 #4
0
        public async Task <ActionResult> Edit(DepartmentEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                var de = await DepartmentManager.FindEntityByIdAsync(model.Id);

                if (de != null)
                {
                    if (!string.IsNullOrEmpty(model.Name))
                    {
                        de.Name = model.Name;
                    }
                    await DepartmentManager.UpdateEntityAsync(de);

                    await MajorManager.SetMajorsDepartmentAsync(model.IdsToAdd ?? new int[] { }, de);

                    await MajorManager.ResetMajorsDepartmentAsync(model.IdsToRemove ?? new int[] { });

                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(View("Error", new[] { "学院不存在" }));
                }
            }
            return(View(model));
        }
コード例 #5
0
        // GET: Departments/Edit/5
        public async Task <IActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            DepartmentEditViewModel departmentEditVM = new DepartmentEditViewModel();

            departmentEditVM.Department = await _context.Departments
                                                          //.Include(d => d.Administrator)  // eager loading
                                          .AsNoTracking() // tracking not required
                                          .FirstOrDefaultAsync(m => m.DepartmentID == id);

            if (departmentEditVM.Department == null)
            {
                return(NotFound());
            }

            // Use strongly typed data rather than ViewData.
            departmentEditVM.InstructorNameSL = new SelectList(_context.Instructors, "ID", "LastName",
                                                               departmentEditVM.Department.InstructorID);

            //ViewData["InstructorID"] = new SelectList(_context.Instructors, "ID", "LastName", department.InstructorID);

            return(View(departmentEditVM));
        }
コード例 #6
0
        public ActionResult Edit(DepartmentEditViewModel model)
        {
            var devm = CreateDepartmentEditViewModel(model.Department.Id);

            devm.Department = model.Department;
            devm.Managers   = model.Managers;

            string err = string.Empty;

            if (ModelState.IsValid)
            {
                try
                {
                    _departmentService.EditDepartment(model.Department.Id, model.Department.Number, model.Department.Name,
                                                      _currentUser.Get().LoginName, model.Department.CompanyId);
                    SaveManagers(model);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                    err = ex.Message;
                }
            }
            var res = this.RenderPartialView("Edit", devm);

            return(Json(new
            {
                IsSucceed = ModelState.IsValid,
                Msg = ModelState.IsValid ? ViewResources.SharedStrings.DepartmentsSavingMessage : err,
                viewData = res
            }));
        }
コード例 #7
0
ファイル: SchoolDomain.cs プロジェクト: zanderzhg/Danvic.PSU
        /// <summary>
        /// 获取部门/院系信息
        /// </summary>
        /// <param name="id">部门/院系编号</param>
        /// <param name="context">数据库连接上下文对象</param>
        /// <returns></returns>
        public async Task <DepartmentEditViewModel> GetDepartmentAsync(long id, ApplicationDbContext context)
        {
            var webModel = new DepartmentEditViewModel();

            try
            {
                var model = await SchoolRepository.GetAsync(id, context);

                webModel.Id           = model.Id.ToString();
                webModel.IsBranch     = (EnumType.Branch)(model.IsBranch ? 1 : 0);
                webModel.Address      = model.Address;
                webModel.Email        = model.Email;
                webModel.Introduction = model.Introduction;
                webModel.IsEnabled    = (EnumType.Enable)(model.IsEnabled ? 1 : 0);
                webModel.Name         = model.Name;
                webModel.QQ           = model.QQ;
                webModel.Tel          = model.Tel;
                webModel.Wechat       = model.Wechat;
                webModel.Weibo        = model.Weibo;
            }
            catch (Exception ex)
            {
                _logger.LogError("获取部门/院系数据失败:{0},\r\n内部错误信息:{1}", ex.Message, ex.InnerException.Message);
            }
            return(webModel);
        }
コード例 #8
0
        public async Task <ActionResult> EditDepartment(DepartmentEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                var de = await InstitutionManager.FindDepartmentByIdAsync(model.Id);

                if (de != null)
                {
                    if (!string.IsNullOrEmpty(model.Name))
                    {
                        de.Name = model.Name;
                    }
                    await InstitutionManager.UpdateDepartmentAsync(de);

                    await InstitutionManager.AddMajorsToDepartmentAsync(de, model.IdsToAdd ?? new int[] { });

                    await InstitutionManager.RemoveMajorsFromDepartmentAsync(de, model.IdsToRemove ?? new int[] { });

                    return(RedirectToAction("AllDepartment"));
                }
                else
                {
                    ModelState.AddModelError("", "学院不存在");
                }
            }
            return(View(model));
        }
コード例 #9
0
        // GET: Department/Edit/8
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                //change to redirect to
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            //Debug Purpose to see if we are getting the id
            Debug.WriteLine("I'm pulling data of " + id.ToString());

            //Get the specific department
            Department department = db.Departments.Find(id);

            //Could not find the specific department
            if (department == null)
            {
                return(HttpNotFound());
            }

            //Must create a view model of the department data
            DepartmentEditViewModel departmentEditViewModel = new DepartmentEditViewModel();

            departmentEditViewModel.id   = department.departmentId;
            departmentEditViewModel.name = department.departmentName;

            //return the department data
            return(View(departmentEditViewModel));
        }
コード例 #10
0
        public ActionResult Edit(DepartmentEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                //Debug Purpose to see if we are getting the data
                Debug.WriteLine("I'm pulling data of " + model.name);

                if (model.name != "")
                {
                    //The query to update a new Department
                    string         query     = "UPDATE Departments SET departmentName = @departmentName WHERE departmentId = @departmentId";
                    SqlParameter[] sqlparams = new SqlParameter[2];
                    sqlparams[0] = new SqlParameter("@departmentName", model.name);
                    sqlparams[1] = new SqlParameter("@departmentId", model.id);

                    //Run the sql command
                    db.Database.ExecuteSqlCommand(query, sqlparams);

                    //Go back to the list of Department to see the edited Department
                    return(RedirectToAction("Index"));
                }
            }

            //Something failed, redisplay form
            return(View(model));
        }
コード例 #11
0
        public DepartmentEditViewModel Add(DepartmentEditViewModel DepartmentEditViewModel)
        {
            Department Department = DepartmentRepo.Add(DepartmentEditViewModel.ToModel());

            unitOfWork.commit();
            return(Department.ToEditableViewModel());
        }
コード例 #12
0
        public async Task <IActionResult> EditDepartment(DepartmentEditViewModel webModel)
        {
            if (ModelState.IsValid)
            {
                bool flag;
                if (string.IsNullOrEmpty(webModel.Id))
                {
                    //Add Department
                    flag = await _service.InsertDepartmentAsync(webModel, _context);
                }
                else
                {
                    //Update Department
                    flag = await _service.UpdateDepartmentAsync(webModel, _context);
                }

                return(Json(new
                {
                    success = flag,
                    msg = flag ? "部门/院系信息编辑成功" : "部门/院系信息编辑失败"
                }));
            }

            return(Json(new
            {
                success = false,
                msg = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors).FirstOrDefault().ErrorMessage
            }));
        }
コード例 #13
0
        void DepartmentGrid_OnBtnEditClicked(object sender, EventArgs e)
        {
            int id    = int.Parse(this.GetIdFromBtnSender(sender));
            var model = new DepartmentEditViewModel();

            this.GetById(id, ref model);
            this.FormCreaterEdit.CreateForm(model);
        }
コード例 #14
0
        public DepartmentEditViewModel Update(DepartmentEditViewModel DepartmentEditViewModel)
        {
            Department department  = DepartmentEditViewModel.ToModel();
            Department _Department = DepartmentRepo.Update(department);

            unitOfWork.commit();
            return(_Department.ToEditableViewModel());
        }
コード例 #15
0
        /// <summary>
        /// 新增院系信息
        /// </summary>
        /// <param name="webModel">院系编辑页视图模型</param>
        /// <param name="context">数据库上下文对象</param>
        /// <returns></returns>
        public static async Task <Department> InsertAsync(DepartmentEditViewModel webModel, ApplicationDbContext context)
        {
            Department model = InsertModel(webModel);

            await context.Department.AddAsync(model);

            return(model);
        }
コード例 #16
0
        public async Task <DepartmentEditViewModel> CreateDepartmentEditViewModel()
        {
            var department = new DepartmentEditViewModel()
            {
                DepartmentId = Guid.NewGuid().ToString(),
                Faculties    = await GetFaculties(),
            };

            return(department);
        }
コード例 #17
0
        /// <summary>
        /// 更新院系信息
        /// </summary>
        /// <param name="webModel">院系编辑页视图模型</param>
        /// <param name="context">数据库上下文对象</param>
        public static async void UpdateAsync(DepartmentEditViewModel webModel, ApplicationDbContext context)
        {
            var model = await context.Department.FirstOrDefaultAsync(i => i.Id == Convert.ToInt64(webModel.Id));

            if (model == null)
            {
                return;
            }

            model = UpdateModel(webModel, model);
        }
コード例 #18
0
        public async Task <DepartmentEditViewModel> CreateDepartmentEditViewModel(Department department)
        {
            var departmentEditViewModel = new DepartmentEditViewModel()
            {
                DepartmentId    = department.Id.ToString(),
                Faculties       = await GetFaculties(),
                DepartmentName  = department.Name,
                SelectedFaculty = department.FacultyId.ToString()
            };

            return(departmentEditViewModel);
        }
コード例 #19
0
        public async Task <IActionResult> EditDepartment(string id)
        {
            DepartmentEditViewModel webModel = new DepartmentEditViewModel();

            if (!string.IsNullOrEmpty(id))
            {
                //编辑信息,加载部门/院系相关信息
                webModel = await _service.GetDepartmentAsync(Convert.ToInt64(id), _context);
            }

            return(View(webModel));
        }
コード例 #20
0
        public RedirectToActionResult Edit(DepartmentEditViewModel department)
        {
            Department newEmployee = _empRepo.GetDepartment(department.DepartmentId);

            newEmployee.DepName     = department.DepName;
            newEmployee.DepHod      = department.DepHod;
            newEmployee.DepLocation = department.DepLocation;

            Department em = _empRepo.Edit(newEmployee);

            return(RedirectToAction("AllDetails"));
        }
コード例 #21
0
        public async Task EditPost_ReturnsRedirectToActionResult_Index()
        {
            //mockModelBindingHelperAdaptor.Setup(m => m.TryUpdateModelAsync(It.IsAny<Controller>(), It.IsAny<Department>(), It.IsAny<string>(), It.IsAny<Expression<Func<Department, object>>[]>()))
            //    .Returns(Task.FromResult(true));

            var vm = new DepartmentEditViewModel {
                ID = 1
            };

            var result = await sut.Edit(vm);

            Assert.IsType <RedirectToActionResult>(result);
        }
コード例 #22
0
        public IActionResult Edit(int id)
        {
            Department department = _empRepo.GetDepartment(id);
            DepartmentEditViewModel employeeModel = new DepartmentEditViewModel
            {
                DepartmentId = department.DepartmentId,
                DepName      = department.DepName,
                DepHod       = department.DepHod,
                DepLocation  = department.DepLocation
            };

            return(View(employeeModel));
        }
        // GET: Departments/Details/5
        public ActionResult Details(int id)
        {
            var viewModel = new DepartmentEditViewModel();

            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                               SELECT d.Id, d.name, d.budget, e.firstName, e.lastName, e.isSupervisor, e.Id as EmployeeId
                                 FROM Department d
                                    Left join Employee e on e.DepartmentId = d.id
                                    WHERE @id = d.id
                                    Order by e.isSupervisor desc
                                         ";
                    cmd.Parameters.Add(new SqlParameter("@id", id));
                    SqlDataReader reader = cmd.ExecuteReader();

                    Department department = new Department();
                    while (reader.Read())
                    {
                        if (viewModel.Department == null)
                        {
                            department = new Department
                            {
                                Id     = reader.GetInt32(reader.GetOrdinal("Id")),
                                Name   = reader.GetString(reader.GetOrdinal("name")),
                                Budget = reader.GetInt32(reader.GetOrdinal("budget")),
                            };
                            viewModel.Department = department;
                        }
                        if (!reader.IsDBNull(reader.GetOrdinal("EmployeeId")))
                        {
                            viewModel.Employees.Add(
                                new Employee()
                            {
                                Id           = reader.GetInt32(reader.GetOrdinal("Id")),
                                FirstName    = reader.GetString(reader.GetOrdinal("FirstName")),
                                LastName     = reader.GetString(reader.GetOrdinal("LastName")),
                                DepartmentId = id,
                                IsSupervisor = reader.GetBoolean(reader.GetOrdinal("IsSupervisor"))
                            });
                        }
                    }

                    reader.Close();
                }
            }
            return(View(viewModel));
        }
コード例 #24
0
        public async Task EditPost_ReturnsAViewResult_WithDeletedDepartmentModelError(int id)
        {
            DepartmentEditViewModel vm = new DepartmentEditViewModel {
                ID = id
            };
            var result = await sut.Edit(vm);

            Assert.IsType <ViewResult>(result);
            var model = (DepartmentEditViewModel)((ViewResult)result).Model;

            Assert.Null(model.Name);
            Assert.True(((ViewResult)result).ViewData.ModelState.Count > 0);
            Assert.True(((ViewResult)result).ViewData.ContainsKey("InstructorID"));
        }
コード例 #25
0
        public HttpResponseMessage PutDept(int id, DepartmentEditViewModel model)
        {
            var itemVm = Mapper.Map <DepartmentEditViewModel, Department>(model);
            var suite  = _departmentService.Find(id);

            if (suite != null && itemVm != null)
            {
                _departmentService.Update(id, itemVm);
                _db.SaveChanges();
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }


            return(new HttpResponseMessage(HttpStatusCode.BadRequest));
        }
コード例 #26
0
        public bool Edit(DepartmentModel departmentModel, string title)
        {
            var editingDepartmentVm = new DepartmentEditViewModel(departmentModel, title);
            var editEmployeeWindow  = new DepartmentEditWindow
            {
                DataContext = editingDepartmentVm
            };

            if (editEmployeeWindow.ShowDialog() != true)
            {
                return(false);
            }

            return(true);
        }
コード例 #27
0
        private void SaveManagers(DepartmentEditViewModel model)
        {
            _userDepartmentService.DeleteDepartmentUserWithRole(model.Department.Id, (int)FixedRoleType.DepartmentManager);
            int companyId = _departmentRepository.FindById(model.Department.Id).CompanyId;
            var managers  = _companyService.GetCompanyManagers(companyId);

            foreach (var manager in model.Managers)
            {
                if (manager.UserId.HasValue && managers.ContainsKey(manager.UserId.Value))
                {
                    _userDepartmentService.AddDepartmentManager(manager.UserId.Value, model.Department.Id, DateTime.ParseExact(manager.ValidFrom, "dd.MM.yyyy", CultureInfo.InvariantCulture),
                                                                DateTime.ParseExact(manager.ValidTo, "dd.MM.yyyy", CultureInfo.InvariantCulture));
                }
            }
        }
コード例 #28
0
        public async Task <bool> UpdateDepartment(DepartmentEditViewModel departmentToUpdate)
        {
            if (departmentToUpdate != null)
            {
                var department = new Department()
                {
                    Id        = Guid.Parse(departmentToUpdate.DepartmentId),
                    Name      = departmentToUpdate.DepartmentName,
                    FacultyId = Guid.Parse(departmentToUpdate.SelectedFaculty)
                };
                var response = await _requestSender.SendPostRequestAsync("https://localhost:44389/api/Departments/update", department);

                return(true);
            }

            return(false);
        }
コード例 #29
0
        public async Task <IActionResult> Update(string uid, [FromBody] DepartmentEditViewModel input)
        {
            var user       = User.GetDetails();
            var department = await _unitOfWork.Departments.SingleAsync(uid);

            department.Update(input.Name, input.Code, input.Status, user.Id);

            if (await _unitOfWork.Departments.AnyAsync(department))
            {
                return(BadRequest("Department Already Exists"));
            }

            _unitOfWork.Departments.Update(department);
            await _unitOfWork.CompleteAsync(user.Id);

            return(Ok(department));
        }
コード例 #30
0
        public ActionResult Create(DepartmentEditViewModel model)
        {
            var devm = CreateViewModel <DepartmentEditViewModel>();

            devm.Department.CompanyId = model.Department.CompanyId;
            var building_ids = GetUserBuildings(_buildingRepository, _userRepository);

            var company_ids = from comp in
                              _companyRepository.FindAll(
                c =>
                !c.IsDeleted && c.Active &&
                c.CompanyBuildingObjects.Any(cbo => !cbo.IsDeleted && building_ids.Contains(cbo.BuildingObject.BuildingId)))
                              select comp.Id;

            devm.CompanyList = new SelectList(_companyRepository.FindAll(c => !c.IsDeleted && c.Active && company_ids.Contains(c.Id)), "Id", "Name", devm.Department.CompanyId);
            devm.Department.DepartmentManagersList = _companyService.GetCompanyManagers(devm.Department.CompanyId);

            devm.Department = model.Department;
            devm.Managers   = model.Managers;

            string err = string.Empty;

            if (ModelState.IsValid && model.Department.CompanyId != -1)
            {
                try
                {
                    devm.Department.Id = _departmentService.CreateDepartment(devm.Department.Number, devm.Department.Name,
                                                                             _currentUser.Get().LoginName, devm.Department.CompanyId);
                    SaveManagers(model);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                    err = ex.Message;
                }
            }

            var res = ModelState.IsValid ? "" : this.RenderPartialView("Create", devm);

            return(Json(new
            {
                IsSucceed = ModelState.IsValid,
                Msg = ModelState.IsValid ? ViewResources.SharedStrings.DataSavingMessage : err,
                viewData = res
            }));
        }
コード例 #31
0
        private void OnWorkerDepartmentsChanged(object sender, ListItemsEventArgs<Department> e)
        {
            if (new[] { ChangeAction.Add, ChangeAction.Change }.Contains(e.Action))
                foreach (var d in e.Items)
                {
                    if (d.Id != 0)
                    {
                        Department depForUpdate = null;
                        var existed = departments.AsEnumerable().Traverse(i => i.Childs).FirstOrDefault(i => i.Data.Department.Id == d.Id);
                        if (existed != null)
                        {
                            existed.Data.Department.CopyObjectFrom(d);
                            depForUpdate = existed.Data.Department;
                        }
                        else
                        {
                            var existedParent = departments.AsEnumerable().Traverse(i => i.Childs).FirstOrDefault(i => i.Data.Department.Id == d.ParentId);
                            if (existedParent != null)
                            {
                                var newDep = new DepartmentEditViewModel() { Data = GetStaffingDataForDepartment(d), Parent = existedParent, Owner = this };
                                var existedChildsInTop = departments.Where(i => i.Data.Department.ParentId == d.Id);
                                foreach (var c in existedChildsInTop)
                                {
                                    c.Parent = newDep;
                                    newDep.Childs.Add(c);
                                }
                                existedParent.Childs.Add(newDep);
                                depForUpdate = newDep.Data.Department;
                            }
                            else
                            {
                                var depVM = new DepartmentEditViewModel() { Data = GetStaffingDataForDepartment(d), Parent = this, Owner = this };
                                departments.Add(depVM);
                                depForUpdate = depVM.Data.Department;
                            }
                        }

                        if (depForUpdate != null)
                            employees
                                .Where(e2 => e2.Employee.Stuffing?.DepartmentId == depForUpdate.Id)
                                .ToList()
                                .ForEach(emp => emp.Department = depForUpdate);

                    }
                }
            else
                foreach (var d in e.Items)
                    if (d.Id != 0)
                    {
                        var existed = departments.AsEnumerable().Traverse(i => i.Childs).FirstOrDefault(i => i.Data.Department.Id == d.Id);
                        if (existed != null)
                            existed.Parent?.Childs.Remove(existed);

                        employees
                            .Where(e2 => e2.Employee.Stuffing?.DepartmentId == d.Id)
                            .ToList()
                            .ForEach(emp => emp.Department = null);
                    }

            OnDepartmentsChanged?.Invoke(this, e);
        }
コード例 #32
0
 private void Insert()
 {
     var newDep = new DepartmentEditViewModel(true)
     {
         Data = new DepartmentAndStaffingData(this)
         { 
             Department = new Department()
             {
                 ParentId = null,
                 Name = Properties.Resources.DEPARTMENTEDIT_NewDepartmentName,
             }
         },
         Parent = this,
         Owner = this,
         IsSelected = true,
     };
     departments.Add(newDep);
 }