Пример #1
0
 public static void TransferValidationMessagesTo <IdT>(
     this DomainObjectWithTypedId <IdT> domainObjectWithTypedID, string keyBase,
     ModelStateDictionary modelStateDictionary)
 {
     MvcValidationAdapter.TransferValidationMessagesTo(keyBase, modelStateDictionary,
                                                       domainObjectWithTypedID.ValidationResults());
 }
        /// <summary>
        /// After the model is updated, there may be a number of ModelState errors added by ASP.NET MVC for
        /// and data casting problems that it runs into while binding the object.  This gets rid of those
        /// casting errors and uses the registered IValidator to populate the ModelState with any validation
        /// errors.
        /// </summary>
        protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            foreach (string key in bindingContext.ModelState.Keys)
            {
                for (int i = 0; i < bindingContext.ModelState[key].Errors.Count; i++)
                {
                    ModelError modelError = bindingContext.ModelState[key].Errors[i];

                    // Get rid of all the MVC errors except those associated with parsing info; e.g., parsing DateTime fields
                    if (IsModelErrorAddedByMvc(modelError) && !IsMvcModelBinderFormatException(modelError))
                    {
                        bindingContext.ModelState[key].Errors.RemoveAt(i);
                        // Decrement the counter since we've shortened the list
                        i--;
                    }
                }
            }

            // Transfer any errors exposed by IValidator to the ModelState
            if (bindingContext.Model is IValidatable)
            {
                MvcValidationAdapter.TransferValidationMessagesTo(
                    bindingContext.ModelName, bindingContext.ModelState,
                    ((IValidatable)bindingContext.Model).ValidationResults());
            }
        }
        public void CanTransferValidationMessagesToModelState()
        {
            ModelStateDictionary      modelStateDictionary = new ModelStateDictionary();
            IList <IValidationResult> invalidValues        = new List <IValidationResult>();

            invalidValues.Add(
                new ValidationResult(
                    new InvalidValue("Message 1", typeof(TransactionAttribute), "Property1", "Test 1", null, null)));
            invalidValues.Add(
                new ValidationResult(
                    new InvalidValue("Message 2", typeof(MvcValidationAdapter), "Property2", "Test 2", null, null)));
            invalidValues.Add(
                new ValidationResult(
                    new InvalidValue("Message 3", GetType(), "Property3", "Test 3", null, null)));

            MvcValidationAdapter.TransferValidationMessagesTo(modelStateDictionary, invalidValues);

            Assert.That(modelStateDictionary.Count, Is.EqualTo(3));
            Assert.That(modelStateDictionary["TransactionAttribute.Property1"].Errors[0].ErrorMessage,
                        Is.EqualTo("Message 1"));
            Assert.That(modelStateDictionary["TransactionAttribute.Property1"].Value.AttemptedValue,
                        Is.EqualTo("Test 1"));
            Assert.That(modelStateDictionary["MvcValidationAdapter.Property2"].Errors[0].ErrorMessage,
                        Is.EqualTo("Message 2"));
            Assert.That(modelStateDictionary["MvcValidationAdapter.Property2"].Value.AttemptedValue,
                        Is.EqualTo("Test 2"));
            Assert.That(modelStateDictionary["MvcValidationAdapterTests.Property3"].Errors[0].ErrorMessage,
                        Is.EqualTo("Message 3"));
            Assert.That(modelStateDictionary["MvcValidationAdapterTests.Property3"].Value.AttemptedValue,
                        Is.EqualTo("Test 3"));
        }
Пример #4
0
        public void CanTransferValidationResultsToModelState()
        {
            var validator = new Validator();

            var invalidObject = new SomeObject
            {
                LastName   = null,
                FirstName  = "ThisFirstNameIsTooLong",
                Street     = " ",
                MiddleName = "valid"
            };

            Assert.IsFalse(validator.IsValid(invalidObject));

            var results = validator.ValidationResultsFor(invalidObject);

            Assert.IsNotNull(results);
            Assert.AreEqual(3, results.Count, "Wrong number of validation messages encountered.");

            ModelStateDictionary modelState = new ModelStateDictionary();

            Assert.IsNotNull(modelState);
            Assert.AreEqual(0, modelState.Values.Count);
            MvcValidationAdapter.TransferValidationMessagesTo(modelState, validator.ValidationResultsFor(invalidObject));

            Assert.AreEqual(3, modelState.Values.Count);

            var resultsList = new List <string>();

            foreach (var result in modelState.Values)
            {
                foreach (var errs in result.Errors)
                {
                    resultsList.Add(errs.ErrorMessage);
                }
            }
            var errors = new[]
            {
                "Dude...the name please!!",
                "The Street field is required.",
                "The field FirstName must be a string with a maximum length of 10."
            };

            Assert.AreEqual(resultsList.Count, errors.Length, "Number of error messages do not match");
            foreach (var error in errors)
            {
                Assert.IsTrue(resultsList.Contains(error), "Expected error \"" + error + "\" not found");
            }
        }