예제 #1
0
        private static MvcHtmlString DoFieldsInfoAwareEditor <TModel, TValue>(
            HtmlHelper <TModel> html,
            Expression <Func <TModel, TValue> > expression,
            ModelFieldsAccessibility fieldsInfo,
            Func <MvcHtmlString> displayDelegate
            )
        {
            string property = html.PropertyName(expression);

            if (!fieldsInfo.IsVisible(property))
            {
                return(MvcHtmlString.Empty);
            }

            ViewDataDictionary          viewData         = html.ViewDataContainer.ViewData;
            List <string>               dataKeysToRemove = new List <string>();
            Dictionary <string, object> dataPrevValues   = new Dictionary <string, object>();

            // "Hide" current fields info from new editor
            viewData.PrepareChangeReversal(FormConstants.FieldsInfoKey, dataKeysToRemove, dataPrevValues);
            viewData.Remove(FormConstants.FieldsInfoKey);

            // Augment new additionalViewData with information from fieldsInfo
            if (fieldsInfo.IsComplex(property))
            {
                viewData[FormConstants.FieldsInfoKey] = fieldsInfo.GetSubFieldInfo(property);
            }
            else if (!fieldsInfo.CanBeChangedByUser(property))
            {
                viewData.PrepareChangeReversal(FormConstants.DisabledKey, dataKeysToRemove, dataPrevValues);
                viewData[FormConstants.DisabledKey] = true;
            }

            // Render the editor
            MvcHtmlString result = displayDelegate();

            // Reverse the changes to ViewData
            dataKeysToRemove.ForEach(s => viewData.Remove(s));
            dataPrevValues.ForEach(pair => viewData[pair.Key] = pair.Value);

            return(result);
        }
예제 #2
0
        public ActionResult Edit(int id)
        {
            Election election = db.Elections.Find(id);

            if (election == null)
            {
                return(HttpNotFound());
            }

            CouncilElectionData councilData = null;
            CouncilElectionForm councilForm = null;
            ElectionForm        form;

            if (election.Type == ElectionType.StudentCouncil)
            {
                councilData = db.CouncilElectionData.First(data => data.ElectionId == election.Id);
                form        = councilForm = GenerateFormForCouncil(election, councilData);
            }
            else
            {
                form = GenerateFormForCourseRep(election);
            }

            ModelFieldsAccessibility fieldsInfo = ElectionLifecycleInfo.GetWhatCanBeEditedCouncil(election);

            ViewData[FormConstants.FieldsInfoKey] = fieldsInfo;
            ViewBag.Election = election;

            fieldsInfo.EnsureAllowedDefaultKind(
                ModelFieldsAccessibility.Kind.Editable,
                nameof(AdminElectionsController) + "." + nameof(Edit)
                );

            if (Request.HttpMethod.ToUpper() != "POST")
            {
                // Just show the template
                return(View("Edit", form));
            }

            AntiForgery.Validate();

            // Update the form based on data that we received
            // ReSharper disable once ConvertIfStatementToNullCoalescingExpression - we need the compiler to specify different generic arguments
            if (councilForm != null)
            {
                TryUpdateModel(councilForm);
            }
            else
            {
                TryUpdateModel(form);
            }

            // Get the original form so that we use old values for uneditable fields
            CouncilElectionForm councilOriginalForm = null;
            ElectionForm        originalForm;

            if (councilForm != null)
            {
                originalForm = councilOriginalForm = GenerateFormForCouncil(election, councilData);
            }
            else
            {
                originalForm = GenerateFormForCourseRep(election);
            }

            // Replace all uneditable values with old ones
            fieldsInfo.ReplaceUneditableWithOldValues(form, originalForm);

            // As the role IDs are sent from user, we need to make sure that they weren't changed
            if (councilForm != null && fieldsInfo.CanBeChangedByUser(nameof(CouncilElectionForm.Roles)))
            {
                IEnumerable <int?> initialRoleIds = councilOriginalForm.Roles.Select(role => role.Id);
                IEnumerable <int?> newRoleIds     = councilForm.Roles.Select(role => role.Id);

                if (!initialRoleIds.SequenceEqual(newRoleIds))
                {
                    throw new Exception("The IDs of roles were changed by user input");
                }
            }

            // Validate again (since some rules are relative to other fields and can be affected by operations above)
            TryValidateModel(form);

            // Ignore the failures from uneditable fields
            this.RemoveIgnoredErrors(fieldsInfo);

            if (!ModelState.IsValid)
            {
                // The validation failed so we just display the form again
                return(View("Edit", form));
            }

            // Record the admin action
            AdminActionRecord actionRecord = CreateActionRecord(election, AdminActionRecord.RecordType.Edit);

            actionRecord.SetFormChangeSet(FormChangeSet.Generate(form, originalForm));
            db.AdminActionRecords.Add(actionRecord);

            // Validation passed with the fields that are allowed to change. Persist the changes
            Mapper.Map(form, election);
            if (councilData != null)
            {
                Mapper.Map(form, councilData);
            }

            db.SaveChanges();

            BackgroundJob.Enqueue <SynchronizeDelayedJobsJob>(job => job.Execute(election.Id));
            AuditLogManager.RecordElectionEdit(User, election);

            return(RedirectToAction("Details", new { id }));
        }