public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            ControllerBase controller = filterContext.Controller as ControllerBase;

              if (controller != null)
              {
            string serializedModelState = controller.TempData[Key] as string;

            if (!string.IsNullOrEmpty(serializedModelState))
            {
              IEnumerable<ModelStateWrapper> modelStateWrappers = JsonConvert.DeserializeObject<IEnumerable<ModelStateWrapper>>(serializedModelState, new JsonSerializerSettings() { Error = DeserializationErrorHandler });

              if (modelStateWrappers != null)
              {
            ModelStateDictionary modelState = new ModelStateDictionary();

            foreach (ModelStateWrapper modelStateWrapper in modelStateWrappers)
            {
              ModelState ms = new ModelState();

              ms.ValidationState = modelStateWrapper.ValidationState;
              ms.Value = new ValueProviderResult(modelStateWrapper.Value, modelStateWrapper.Value, null);
              modelState.Add(modelStateWrapper.Key, ms);
            }

            if (filterContext.Result is ViewResult)
              controller.ViewData.ModelState.Merge(modelState);

            else controller.TempData.Remove(Key);
              }
            }
              }

              base.OnActionExecuted(filterContext);
        }
예제 #2
0
        public void ValueHelpersWithErrorsGetValueFromModelState()
        {
            // Arrange
            var model = new TestModel()
            {
                StringProperty = "ModelStringPropertyValue",
                ObjectProperty = "ModelObjectPropertyValue",
            };
            var helper = DefaultTemplatesUtilities.GetHtmlHelper<TestModel>(model);
            var viewData = helper.ViewData;
            viewData["StringProperty"] = "ViewDataValue";
            viewData.TemplateInfo.HtmlFieldPrefix = "FieldPrefix";

            var modelState = new ModelState();
            modelState.Value = new ValueProviderResult(
                rawValue: new string[] { "StringPropertyRawValue" },
                attemptedValue: "StringPropertyAttemptedValue",
                culture: CultureInfo.InvariantCulture);
            viewData.ModelState["FieldPrefix.StringProperty"] = modelState;

            modelState = new ModelState();
            modelState.Value = new ValueProviderResult(
                rawValue: new string[] { "ModelRawValue" },
                attemptedValue: "ModelAttemptedValue",
                culture: CultureInfo.InvariantCulture);
            viewData.ModelState["FieldPrefix"] = modelState;

            // Act & Assert
            Assert.Equal("StringPropertyRawValue", helper.Value("StringProperty"));
            Assert.Equal("StringPropertyRawValue", helper.ValueFor(m => m.StringProperty));
            Assert.Equal("ModelRawValue", helper.ValueForModel());
        }
예제 #3
0
        public static string GetUserErrorMessageOrDefault(ModelError modelError, ModelState modelState)
        {
            if (!string.IsNullOrEmpty(modelError.ErrorMessage))
            {
                return modelError.ErrorMessage;
            }

            if (modelState == null)
            {
                return string.Empty;
            }

            var attemptedValue = modelState.AttemptedValue ?? "null";
            return Resources.FormatCommon_ValueNotValidForProperty(attemptedValue);
        }
예제 #4
0
        public void MarkFieldSkipped_MarksFieldAsSkipped_IfStateIsNotInValid(ModelValidationState validationState)
        {
            // Arrange
            var modelState = new ModelState
            {
                ValidationState = validationState
            };

            var source = new ModelStateDictionary
            {
                { "key",  modelState }
            };

            // Act
            source.MarkFieldSkipped("key");

            // Assert
            Assert.Equal(ModelValidationState.Skipped, source["key"].ValidationState);
        }
예제 #5
0
        public void MarkFieldSkipped_MarksFieldAsSkipped_IfKeyIsNotPresent()
        {
            // Arrange
            var modelState = new ModelState
            {
                ValidationState = ModelValidationState.Valid
            };

            var source = new ModelStateDictionary
            {
            };

            // Act
            source.MarkFieldSkipped("key");

            // Assert
            Assert.Equal(0, source.ErrorCount);
            Assert.Equal(1, source.Count);
            Assert.Equal(ModelValidationState.Skipped, source["key"].ValidationState);
        }
예제 #6
0
        public void MarkFieldSkipped_Throws_IfStateIsInvalid()
        {
            // Arrange
            var modelState = new ModelState
            {
                ValidationState = ModelValidationState.Invalid
            };

            var source = new ModelStateDictionary
            {
                { "key",  modelState }
            };

            // Act
            var exception = Assert.Throws<InvalidOperationException>(() => source.MarkFieldSkipped("key"));

            // Assert
            Assert.Equal(
                "A field previously marked invalid should not be marked skipped.",
                exception.Message);
        }
        public void ModelStateDictionary_ClearEntriesPrefixedWithKey_NonEmptyKey()
        {
            // Arrange
            var dictionary = new ModelStateDictionary();

            dictionary["Product"] = new ModelState { ValidationState = ModelValidationState.Valid };

            dictionary["Product.Detail1"] = new ModelState { ValidationState = ModelValidationState.Invalid };
            dictionary.AddModelError("Product.Detail1", "Product Detail1 invalid.");

            dictionary["Product.Detail2[0]"] = new ModelState { ValidationState = ModelValidationState.Invalid };
            dictionary.AddModelError("Product.Detail2[0]", "Product Detail2[0] invalid.");

            dictionary["Product.Detail2[1]"] = new ModelState { ValidationState = ModelValidationState.Invalid };
            dictionary.AddModelError("Product.Detail2[1]", "Product Detail2[1] invalid.");

            dictionary["Product.Detail2[2]"] = new ModelState { ValidationState = ModelValidationState.Skipped };

            dictionary["Product.Detail3"] = new ModelState { ValidationState = ModelValidationState.Skipped };

            dictionary["ProductName"] = new ModelState { ValidationState = ModelValidationState.Invalid };
            dictionary.AddModelError("ProductName", "ProductName invalid.");

            // Act
            dictionary.ClearValidationState("Product");

            // Assert
            Assert.Equal(0, dictionary["Product"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Product"].ValidationState);
            Assert.Equal(0, dictionary["Product.Detail1"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Product.Detail1"].ValidationState);
            Assert.Equal(0, dictionary["Product.Detail2[0]"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Product.Detail2[0]"].ValidationState);
            Assert.Equal(0, dictionary["Product.Detail2[1]"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Product.Detail2[1]"].ValidationState);
            Assert.Equal(0, dictionary["Product.Detail2[2]"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Product.Detail2[2]"].ValidationState);
            Assert.Equal(0, dictionary["Product.Detail3"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Product.Detail3"].ValidationState);
            Assert.Equal(1, dictionary["ProductName"].Errors.Count);
            Assert.Equal(ModelValidationState.Invalid, dictionary["ProductName"].ValidationState);
        }
        public void IsValidPropertyReturnsFalse_IfSomeFieldsAreNotValidated()
        {
            // Arrange
            var errorState = new ModelState
            {
                Value = GetValueProviderResult("quux", "quux"),
                ValidationState = ModelValidationState.Invalid
            };
            var validState = new ModelState
            {
                Value = GetValueProviderResult("bar", "bar"),
                ValidationState = ModelValidationState.Valid
            };
            errorState.Errors.Add("some error");
            var dictionary = new ModelStateDictionary()
            {
                { "foo", validState },
                { "baz", errorState },
                { "qux", new ModelState { Value = GetValueProviderResult() }}
            };

            // Act
            var isValid = dictionary.IsValid;
            var validationState = dictionary.ValidationState;

            // Assert
            Assert.False(isValid);
            Assert.Equal(ModelValidationState.Unvalidated, validationState);
        }
        public void ModelStateDictionary_ClearEntriesThatMatchWithKey_NonEmptyKey()
        {
            // Arrange
            var dictionary = new ModelStateDictionary();

            dictionary["Property1"] = new ModelState { ValidationState = ModelValidationState.Valid };

            dictionary["Property2"] = new ModelState { ValidationState = ModelValidationState.Invalid };
            dictionary.AddModelError("Property2", "Property2 invalid.");

            dictionary["Property3"] = new ModelState { ValidationState = ModelValidationState.Invalid };
            dictionary.AddModelError("Property3", "Property invalid.");

            dictionary["Property4"] = new ModelState { ValidationState = ModelValidationState.Skipped };

            // Act
            dictionary.ClearValidationState("Property1");
            dictionary.ClearValidationState("Property2");
            dictionary.ClearValidationState("Property4");

            // Assert
            Assert.Equal(0, dictionary["Property1"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Property1"].ValidationState);
            Assert.Equal(0, dictionary["Property2"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Property2"].ValidationState);
            Assert.Equal(1, dictionary["Property3"].Errors.Count);
            Assert.Equal(ModelValidationState.Invalid, dictionary["Property3"].ValidationState);
            Assert.Equal(0, dictionary["Property4"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Property4"].ValidationState);
        }
        public void RemoveAll_ForNotModelsExpression_RemovesModelStateKeys()
        {
            // Arrange
            var variable = "Test";
            var state = new ModelState();
            var dictionary = new ModelStateDictionary();

            dictionary.Add("Key", state);
            dictionary.Add("variable", new ModelState());
            dictionary.Add("variable.Text", new ModelState());
            dictionary.Add("variable.Value", new ModelState());

            // Act
            dictionary.RemoveAll<TestModel>(model => variable);

            // Assert
            var modelState = Assert.Single(dictionary);

            Assert.Equal("Key", modelState.Key);
            Assert.Same(state, modelState.Value);
        }
        public void RemoveAll_ForImplicitlyCastedToObjectExpression_RemovesModelStateKeys()
        {
            // Arrange
            var state = new ModelState();
            var dictionary = new ModelStateDictionary();

            dictionary.Add("Child", state);
            dictionary.Add("Child.Value", new ModelState());

            // Act
            dictionary.RemoveAll<TestModel>(model => model.Child.Value);

            // Assert
            var modelState = Assert.Single(dictionary);

            Assert.Equal("Child", modelState.Key);
            Assert.Same(state, modelState.Value);
        }
        public void RemoveAll_ForModelExpression_RemovesModelPropertyKeys()
        {
            // Arrange
            var state = new ModelState();
            var dictionary = new ModelStateDictionary();

            dictionary.Add("Key", state);
            dictionary.Add("Text", new ModelState());
            dictionary.Add("Child", new ModelState());
            dictionary.Add("Child.Text", new ModelState());
            dictionary.Add("Child.NoValue", new ModelState());

            // Act
            dictionary.RemoveAll<TestModel>(model => model);

            // Assert
            var modelState = Assert.Single(dictionary);

            Assert.Equal("Key", modelState.Key);
            Assert.Same(state, modelState.Value);
        }
예제 #13
0
        private ModelState CreateValidModelState(string value)
        {
            ModelState modelState = new ModelState();

              modelState.ValidationState = ModelValidationState.Valid;
              modelState.Value = new ValueProviderResult(value, value, null);
              return modelState;
        }
        public void ModelStateDictionary_ClearsAllEntries_EmptyKey(string modelKey)
        {
            // Arrange
            var dictionary = new ModelStateDictionary();

            dictionary["Property1"] = new ModelState { ValidationState = ModelValidationState.Valid };

            dictionary["Property2"] = new ModelState { ValidationState = ModelValidationState.Invalid };
            dictionary.AddModelError("Property2", "Property2 invalid.");

            dictionary["Property3"] = new ModelState { ValidationState = ModelValidationState.Invalid };
            dictionary.AddModelError("Property3", "Property invalid.");

            dictionary["Property4"] = new ModelState { ValidationState = ModelValidationState.Skipped };

            // Act
            dictionary.ClearValidationState(modelKey);

            // Assert
            Assert.Equal(0, dictionary["Property1"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Property1"].ValidationState);
            Assert.Equal(0, dictionary["Property2"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Property2"].ValidationState);
            Assert.Equal(0, dictionary["Property3"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Property3"].ValidationState);
            Assert.Equal(0, dictionary["Property4"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Property4"].ValidationState);
        }
        public void ModelStateDictionary_ClearEntries_KeyHasDot_NonEmptyKey()
        {
            // Arrange
            var dictionary = new ModelStateDictionary();

            dictionary["Product"] = new ModelState { ValidationState = ModelValidationState.Valid };

            dictionary["Product.Detail1"] = new ModelState { ValidationState = ModelValidationState.Invalid };
            dictionary.AddModelError("Product.Detail1", "Product Detail1 invalid.");

            dictionary["Product.Detail1.Name"] = new ModelState { ValidationState = ModelValidationState.Invalid };
            dictionary.AddModelError("Product.Detail1.Name", "Product Detail1 Name invalid.");

            dictionary["Product.Detail1Name"] = new ModelState { ValidationState = ModelValidationState.Skipped };

            // Act
            dictionary.ClearValidationState("Product.Detail1");

            // Assert
            Assert.Equal(ModelValidationState.Valid, dictionary["Product"].ValidationState);
            Assert.Equal(0, dictionary["Product.Detail1"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Product.Detail1"].ValidationState);
            Assert.Equal(0, dictionary["Product.Detail1.Name"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Product.Detail1.Name"].ValidationState);
            Assert.Equal(ModelValidationState.Skipped, dictionary["Product.Detail1Name"].ValidationState);
        }
예제 #16
0
        public void ValueHelpersWithErrorsGetValueFromModelState()
        {
            // Arrange
            var model = new TestModel()
            {
                StringProperty = "ModelStringPropertyValue",
                ObjectProperty = "ModelObjectPropertyValue",
            };
            var helper = DefaultTemplatesUtilities.GetHtmlHelper<TestModel>(model);
            var viewData = helper.ViewData;
            viewData["StringProperty"] = "ViewDataValue";
            viewData.TemplateInfo.HtmlFieldPrefix = "FieldPrefix";

            var modelState = new ModelState();
            modelState.AttemptedValue = "StringPropertyAttemptedValue";
            modelState.RawValue = new string[] { "StringPropertyRawValue" };
            viewData.ModelState["FieldPrefix.StringProperty"] = modelState;

            modelState = new ModelState();
            modelState.AttemptedValue = "ModelAttemptedValue";
            modelState.RawValue = new string[] { "ModelRawValue" };
            viewData.ModelState["FieldPrefix"] = modelState;

            // Act & Assert
            Assert.Equal("StringPropertyRawValue", helper.Value("StringProperty", format: null));
            Assert.Equal("StringPropertyRawValue", helper.ValueFor(m => m.StringProperty, format: null));
            Assert.Equal("ModelRawValue", helper.ValueForModel(format: null));
        }
예제 #17
0
        public void IsValidPropertyReturnsFalseIfErrors()
        {
            // Arrange
            var errorState = new ModelState
            {
                ValidationState = ModelValidationState.Invalid
            };
            var validState = new ModelState
            {
                ValidationState = ModelValidationState.Valid
            };
            errorState.Errors.Add("some error");
            var dictionary = new ModelStateDictionary()
            {
                { "foo", validState },
                { "baz", errorState }
            };

            // Act
            var isValid = dictionary.IsValid;
            var validationState = dictionary.ValidationState;

            // Assert
            Assert.False(isValid);
            Assert.Equal(ModelValidationState.Invalid, validationState);
        }
예제 #18
0
        public void GetFieldValidationState_ReturnsValidIfModelStateDoesNotContainErrors(string key)
        {
            // Arrange
            var validState = new ModelState
            {
                ValidationState = ModelValidationState.Valid
            };
            var msd = new ModelStateDictionary
            {
                { key, validState }
            };

            // Act
            var validationState = msd.GetFieldValidationState("foo");

            // Assert
            Assert.Equal(ModelValidationState.Valid, validationState);
        }
        public void MarkFieldValid_MarksFieldAsValid_IfStateIsNotInvalid(ModelValidationState validationState)
        {
            // Arrange
            var modelState = new ModelState
            {
                Value = GetValueProviderResult("value"),
                ValidationState = validationState
            };

            var source = new ModelStateDictionary
            {
                { "key",  modelState }
            };

            // Act
            source.MarkFieldValid("key");

            // Assert
            Assert.Equal(ModelValidationState.Valid, source["key"].ValidationState);
        }
예제 #20
0
        private ModelState CreateValidModelState(string value)
        {
            ModelState modelState = new ModelState();

              modelState.ValidationState = ModelValidationState.Valid;
              modelState.AttemptedValue = value;
              return modelState;
        }
예제 #21
0
        public void DisplayTextFor_IgnoresModelStateEntry()
        {
            // Arrange
            var model = new OverriddenToStringModel("Model value")
            {
                Name = "Property value",
            };
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(model);
            var viewData = helper.ViewData;
            viewData["Name"] = "View data dictionary value";
            viewData.TemplateInfo.HtmlFieldPrefix = "FieldPrefix";

            var modelState = new ModelState();
            modelState.RawValue = new string[] { "Attempted name value" };
            modelState.AttemptedValue = "Attempted name value";
            viewData.ModelState["FieldPrefix.Name"] = modelState;

            // Act
            var result = helper.DisplayTextFor(m => m.Name);

            // Assert
            Assert.Equal("Property value", result);
        }
        public void DisplayText_ReturnsModelStateEntry()
        {
            // Arrange
            var model = new OverriddenToStringModel("Model value")
            {
                Name = "Property value",
            };
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(model);
            var viewData = helper.ViewData;
            viewData["Name"] = "View data dictionary value";
            viewData.TemplateInfo.HtmlFieldPrefix = "FieldPrefix";

            var modelState = new ModelState();
            modelState.Value = new ValueProviderResult(
                rawValue: new string[] { "Attempted name value" },
                attemptedValue: "Attempted name value",
                culture: CultureInfo.InvariantCulture);
            viewData.ModelState["FieldPrefix.Name"] = modelState;

            // Act
            var result = helper.DisplayText("Name");

            // Assert
            Assert.Equal("View data dictionary value", result);
        }
예제 #23
0
        private void HandleViewModelMultilingualProperties(ActionExecutingContext actionExecutingContext)
        {
            ViewModelBase viewModel = this.GetViewModelFromActionExecutingContext(actionExecutingContext);

              if (viewModel == null)
            return;

              try
              {
            IEnumerable<Culture> cultures = this.Storage.GetRepository<ICultureRepository>().All();

            foreach (PropertyInfo propertyInfo in this.GetMultilingualPropertiesFromViewModel(viewModel))
            {
              this.ModelState.Remove(propertyInfo.Name);

              bool hasRequiredAttribute = propertyInfo.CustomAttributes.Any(ca => ca.AttributeType == typeof(RequiredAttribute));

              foreach (Culture culture in cultures)
              {
            string identity = propertyInfo.Name + culture.Code;
            string value = this.Request.Form[identity];

            ModelState modelState = new ModelState();

            if (hasRequiredAttribute && string.IsNullOrEmpty(value))
              this.ModelState.Add(identity, this.CreateInvalidModelState(value));

            else this.ModelState.Add(identity, this.CreateValidModelState(value));
              }
            }
              }

              catch { }
        }
        public void CopyConstructor_CopiesModelStateData()
        {
            // Arrange
            var modelState = new ModelState
            {
                Value = GetValueProviderResult("value")
            };
            var source = new ModelStateDictionary
            {
                { "key",  modelState }
            };

            // Act
            var target = new ModelStateDictionary(source);

            // Assert
            Assert.Equal(0, target.ErrorCount);
            Assert.Equal(1, target.Count);
            Assert.Same(modelState, target["key"]);
            Assert.IsType<CopyOnWriteDictionary<string, ModelState>>(target.InnerDictionary);
        }
        public void ClearValidationStateForModel_EmtpyModelKey(string modelKey)
        {
            // Arrange
            var metadataProvider = new EmptyModelMetadataProvider();
            var dictionary = new ModelStateDictionary();
            dictionary["Name"] = new ModelState { ValidationState = ModelValidationState.Invalid };
            dictionary.AddModelError("Name", "MyProperty invalid.");
            dictionary["Id"] = new ModelState { ValidationState = ModelValidationState.Invalid };
            dictionary.AddModelError("Id", "Id invalid.");
            dictionary.AddModelError("Id", "Id is required.");
            dictionary["Category"] = new ModelState { ValidationState = ModelValidationState.Valid };

            // Act
            ModelBindingHelper.ClearValidationStateForModel(
                typeof(Product),
                dictionary,
                metadataProvider,
                modelKey);

            // Assert
            Assert.Equal(0, dictionary["Name"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Name"].ValidationState);
            Assert.Equal(0, dictionary["Id"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Id"].ValidationState);
            Assert.Equal(0, dictionary["Category"].Errors.Count);
            Assert.Equal(ModelValidationState.Unvalidated, dictionary["Category"].ValidationState);
        }
        public void GetFieldValidationState_IndexedPrefix_ReturnsValidIfModelStateDoesNotContainErrors(string key)
        {
            // Arrange
            var validState = new ModelState
            {
                Value = new ValueProviderResult(null, null, null),
                ValidationState = ModelValidationState.Valid
            };
            var msd = new ModelStateDictionary
            {
                { key, validState }
            };

            // Act
            var validationState = msd.GetFieldValidationState("[0].foo");

            // Assert
            Assert.Equal(ModelValidationState.Valid, validationState);
        }
예제 #27
0
        public void ValueHelpersDoNotEncodeValue()
        {
            // Arrange
            var model = new TestModel { StringProperty = "ModelStringPropertyValue <\"\">" };
            var helper = DefaultTemplatesUtilities.GetHtmlHelper<TestModel>(model);
            var viewData = helper.ViewData;
            viewData["StringProperty"] = "ViewDataValue <\"\">";

            var modelState = new ModelState();
            modelState.Value = new ValueProviderResult(
                rawValue: new string[] { "ObjectPropertyRawValue <\"\">" },
                attemptedValue: "ObjectPropertyAttemptedValue <\"\">",
                culture: CultureInfo.InvariantCulture);
            viewData.ModelState["ObjectProperty"] = modelState;

            // Act & Assert
            Assert.Equal(
                "<{ StringProperty = ModelStringPropertyValue <\"\">, ObjectProperty = (null) }>",
                helper.ValueForModel("<{0}>"));
            Assert.Equal("<ViewDataValue <\"\">>", helper.Value("StringProperty", "<{0}>"));
            Assert.Equal("<ModelStringPropertyValue <\"\">>", helper.ValueFor(m => m.StringProperty, "<{0}>"));
            Assert.Equal("ObjectPropertyRawValue <\"\">", helper.ValueFor(m => m.ObjectProperty, format: null));
        }
        public void RemoveAll_ForSingleExpression_RemovesModelStateKeys()
        {
            // Arrange
            var state = new ModelState();
            var dictionary = new ModelStateDictionary();

            dictionary.Add("Key", state);
            dictionary.Add("Text", new ModelState());
            dictionary.Add("Text.Length", new ModelState());

            // Act
            dictionary.RemoveAll<TestModel>(model => model.Text);

            // Assert
            var modelState = Assert.Single(dictionary);

            Assert.Equal("Key", modelState.Key);
            Assert.Same(state, modelState.Value);
        }