Ejemplo n.º 1
0
        public void CheckBoxForWithNonNullContainer_UsesPropertyValue(bool value, string expectedChecked)
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected =
                $@"<input {{0}}data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
                @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";

            expected = string.Format(expected, expectedChecked);

            var viewData = GetTestModelViewData();

            viewData.Model = new TestModel
            {
                Property1 = value,
            };

            var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);

            // Act
            var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 2
0
        public void CheckBox_WithCanRenderAtEndOfFormSet_DoesNotGenerateInlineHiddenTag()
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
            var expected        = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
                                  $@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property1]]"" " +
                                  @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" " +
                                  @"value=""HtmlEncode[[true]]"" />";
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());

            helper.ViewContext.FormContext.CanRenderAtEndOfForm = true;

            // Act
            var html = helper.CheckBox("Property1", isChecked: true, htmlAttributes: null);

            // Assert
            Assert.True(helper.ViewContext.FormContext.HasEndOfFormContent);
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
            var writer    = new StringWriter();
            var hiddenTag = Assert.Single(helper.ViewContext.FormContext.EndOfFormContent);

            hiddenTag.WriteTo(writer, new HtmlTestEncoder());
            Assert.Equal("<input name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[hidden]]\" value=\"HtmlEncode[[false]]\" />",
                         writer.ToString());
        }
Ejemplo n.º 3
0
        public void MultipleValidationErrorsOnSameMemberReported()
        {
            // Arrange
            var model = new Address()
            {
                Street = "Microsoft Way"
            };
            var testValidationContext = GetModelValidationContext(model, model.GetType());
            var validationContext     = testValidationContext.ModelValidationContext;

            // Act (does not throw)
            new DefaultObjectValidator(
                testValidationContext.ExcludeFiltersProvider,
                testValidationContext.ModelMetadataProvider)
            .Validate(validationContext);

            // Assert
            Assert.Contains("Street", validationContext.ModelState.Keys);
            var streetState = validationContext.ModelState["Street"];

            Assert.Equal(2, streetState.Errors.Count);
            var errorCollection = streetState.Errors.Select(e => e.ErrorMessage);

            Assert.Contains(ValidationAttributeUtil.GetStringLengthErrorMessage(null, 5, "Street"), errorCollection);
            Assert.Contains(ValidationAttributeUtil.GetRegExErrorMessage("hehehe", "Street"), errorCollection);
        }
        public void Validate_ComplexReferenceType_Invalid()
        {
            // Arrange
            var actionContext   = new ActionContext();
            var modelState      = actionContext.ModelState;
            var validationState = new ValidationStateDictionary();

            var validator = CreateValidator();

            var model = (object)new Person();

            validationState.Add(model, new ValidationStateEntry()
            {
                Key = string.Empty
            });

            // Act
            validator.Validate(actionContext, validationState, string.Empty, model);

            // Assert
            Assert.False(modelState.IsValid);
            AssertKeysEqual(modelState, "Name", "Profession");

            var entry = modelState["Name"];

            Assert.Equal(ModelValidationState.Invalid, entry.ValidationState);
            var error = Assert.Single(entry.Errors);

            Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("Name"), error.ErrorMessage);

            entry = modelState["Profession"];
            Assert.Equal(ModelValidationState.Invalid, entry.ValidationState);
            error = Assert.Single(entry.Errors);
            Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("Profession"), error.ErrorMessage);
        }
        public async Task CollectionModelBinder_BindsCollectionOfComplexType_ImpliedPrefix_FindsValidationErrors(
            string queryString)
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name          = "parameter",
                ParameterType = typeof(ICollection <Address5>),
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.QueryString = new QueryString(queryString);
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);
            var model   = Assert.IsType <List <Address5> >(modelBindingResult.Model);
            var address = Assert.Single(model);

            Assert.Equal("LongStreet", address.Street);

            Assert.False(modelState.IsValid);

            var entry = Assert.Single(modelState).Value;
            var error = Assert.Single(entry.Errors);

            Assert.Equal(ValidationAttributeUtil.GetStringLengthErrorMessage(null, 3, "Street"), error.ErrorMessage);
        }
Ejemplo n.º 6
0
        public void CheckBoxInTemplate_WithEmptyExpression_GeneratesExpectedValue()
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
            var expected        =
                $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
                @"id=""HtmlEncode[[MyPrefix]]"" name=""HtmlEncode[[MyPrefix]]"" " +
                @"Property3=""HtmlEncode[[Property3Value]]"" type=""HtmlEncode[[checkbox]]"" " +
                @"value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[MyPrefix]]"" " +
                @"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(model: false);

            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
            var attributes = new Dictionary <string, object>
            {
                { "Property3", "Property3Value" },
                { "name", "-expression-" }, // overridden
            };

            // Act
            var html = helper.CheckBox(string.Empty, isChecked: false, htmlAttributes: attributes);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
        public void AddValidation_DoesNotTrounceExistingAttributes()
        {
            // Arrange
            var expectedMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Length");
            var provider        = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata        = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new RequiredAttribute();
            var adapter   = new RequiredAttributeAdapter(attribute, stringLocalizer: null);

            var actionContext = new ActionContext();
            var context       = new ClientModelValidationContext(actionContext, metadata, provider, new AttributeDictionary());

            context.Attributes.Add("data-val", "original");
            context.Attributes.Add("data-val-required", "original");

            // Act
            adapter.AddValidation(context);

            // Assert
            Assert.Collection(
                context.Attributes,
                kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("original", kvp.Value); },
                kvp => { Assert.Equal("data-val-required", kvp.Key); Assert.Equal("original", kvp.Value); });
        }
Ejemplo n.º 8
0
        public void TryValidateModel_CollectionsModel_ReturnsErrorsForInvalidProperties()
        {
            // Arrange
            var testContext = ModelBindingTestHelper.GetTestContext();
            var modelState  = testContext.ModelState;
            var model       = new List <ProductViewModel>();

            model.Add(new ProductViewModel()
            {
                Price          = 2,
                Contact        = "acvrdzersaererererfdsfdsfdsfsdf",
                ProductDetails = new ProductDetails()
                {
                    Detail1 = "d1",
                    Detail2 = "d2",
                    Detail3 = "d3"
                }
            });
            model.Add(new ProductViewModel()
            {
                Price          = 2,
                Contact        = "acvrdzersaererererfdsfdsfdsfsdf",
                ProductDetails = new ProductDetails()
                {
                    Detail1 = "d1",
                    Detail2 = "d2",
                    Detail3 = "d3"
                }
            });

            var controller = CreateController(testContext, testContext.MetadataProvider);

            // We define the "CompanyName null" message locally, so we should manually check its value.
            var categoryRequired = ValidationAttributeUtil.GetRequiredErrorMessage("Category");
            var priceRange       = ValidationAttributeUtil.GetRangeErrorMessage(20, 100, "Price");
            var contactUsMax     = ValidationAttributeUtil.GetStringLengthErrorMessage(null, 20, "Contact Us");
            var contactUsRegEx   = ValidationAttributeUtil.GetRegExErrorMessage("^[0-9]*$", "Contact Us");

            // Act
            var result = controller.TryValidateModel(model);

            // Assert
            Assert.False(result);
            Assert.False(modelState.IsValid);
            var modelStateErrors = GetModelStateErrors(modelState);

            Assert.Equal("CompanyName cannot be null or empty.", modelStateErrors["[0].CompanyName"]);
            Assert.Equal(priceRange, modelStateErrors["[0].Price"]);
            Assert.Equal(categoryRequired, modelStateErrors["[0].Category"]);
            AssertErrorEquals(contactUsMax + contactUsRegEx, modelStateErrors["[0].Contact"]);
            Assert.Equal("CompanyName cannot be null or empty.", modelStateErrors["[1].CompanyName"]);
            Assert.Equal(priceRange, modelStateErrors["[1].Price"]);
            Assert.Equal(categoryRequired, modelStateErrors["[1].Category"]);
            AssertErrorEquals(contactUsMax + contactUsRegEx, modelStateErrors["[1].Contact"]);
        }
Ejemplo n.º 9
0
    public void PasswordFor_GeneratesUnobtrusiveValidationAttributes()
    {
        // Arrange
        var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property2");
        var expected        =
            $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
            @"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[password]]"" />";
        var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithErrors());

        // Act
        var result = helper.PasswordFor(m => m.Property2, htmlAttributes: null);

        // Assert
        Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
    }
        public async Task ModelMetadataTypeAttribute_InvalidPropertiesAndSubPropertiesOnBaseClass_HasModelStateErrors()
        {
            // Arrange
            var input           = "{ \"Price\": 2, \"ProductDetails\": {\"Detail1\": \"d1\"}}";
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BindingSource = BindingSource.Body
                },
                ParameterType = typeof(ProductViewModel)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                request.Body        = new MemoryStream(Encoding.UTF8.GetBytes(input));
                request.ContentType = "application/json";
            });

            var modelState = testContext.ModelState;

            var priceRange        = ValidationAttributeUtil.GetRangeErrorMessage(20, 100, "Price");
            var categoryRequired  = ValidationAttributeUtil.GetRequiredErrorMessage("Category");
            var contactUsRequired = ValidationAttributeUtil.GetRequiredErrorMessage("Contact Us");
            var detail2Required   = ValidationAttributeUtil.GetRequiredErrorMessage("Detail2");
            var detail3Required   = ValidationAttributeUtil.GetRequiredErrorMessage("Detail3");

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);
            var boundPerson = Assert.IsType <ProductViewModel>(modelBindingResult.Model);

            Assert.NotNull(boundPerson);
            Assert.False(modelState.IsValid);
            var modelStateErrors = CreateValidationDictionary(modelState);

            Assert.Equal("CompanyName cannot be null or empty.", modelStateErrors["CompanyName"]);
            Assert.Equal(priceRange, modelStateErrors["Price"]);
            Assert.Equal(categoryRequired, modelStateErrors["Category"]);
            Assert.Equal(contactUsRequired, modelStateErrors["Contact"]);
            Assert.Equal(detail2Required, modelStateErrors["ProductDetails.Detail2"]);
            Assert.Equal(detail3Required, modelStateErrors["ProductDetails.Detail3"]);
        }
Ejemplo n.º 11
0
        public void CheckBoxGeneratesUnobtrusiveValidationAttributes()
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Name");
            var expected        =
                $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Name]]""" +
                @" name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                @"<input name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData());

            // Act
            var html = helper.CheckBox("Name", isChecked: null, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 12
0
        public void CheckBoxCheckedWithOnlyName_GeneratesExpectedValue()
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
            var expected        = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
                                  $@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property1]]"" " +
                                  @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" " +
                                  @"value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());

            // Act
            var html = helper.CheckBox("Property1", isChecked: true, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
        public void Validate_CollectionType_ListOfComplexType_Invalid()
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var modelState        = new ModelStateDictionary();
            var validationState   = new ValidationStateDictionary();

            var validator = CreateValidator();

            var model = (object)new List <Person> {
                new Person(), new Person()
            };

            validationState.Add(model, new ValidationStateEntry()
            {
                Key = string.Empty
            });

            // Act
            validator.Validate(validatorProvider, modelState, validationState, string.Empty, model);

            // Assert
            Assert.False(modelState.IsValid);
            AssertKeysEqual(modelState, "[0].Name", "[0].Profession", "[1].Name", "[1].Profession");

            var entry = modelState["[0].Name"];

            Assert.Equal(ModelValidationState.Invalid, entry.ValidationState);
            var error = Assert.Single(entry.Errors);

            Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("Name"), error.ErrorMessage);

            entry = modelState["[0].Profession"];
            Assert.Equal(ModelValidationState.Invalid, entry.ValidationState);
            error = Assert.Single(entry.Errors);
            Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("Profession"), error.ErrorMessage);

            entry = modelState["[1].Name"];
            Assert.Equal(ModelValidationState.Invalid, entry.ValidationState);
            error = Assert.Single(entry.Errors);
            Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("Name"), error.ErrorMessage);

            entry = modelState["[1].Profession"];
            Assert.Equal(ModelValidationState.Invalid, entry.ValidationState);
            error = Assert.Single(entry.Errors);
            Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("Profession"), error.ErrorMessage);
        }
        public void Validate_NestedComplexReferenceType_Invalid()
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var modelState        = new ModelStateDictionary();
            var validationState   = new ValidationStateDictionary();

            var validator = CreateValidator();

            var model = (object)new Person()
            {
                Name = "Rick", Friend = new Person()
            };

            modelState.SetModelValue("Name", "Rick", "Rick");
            validationState.Add(model, new ValidationStateEntry()
            {
                Key = string.Empty
            });

            // Act
            validator.Validate(validatorProvider, modelState, validationState, string.Empty, model);

            // Assert
            Assert.False(modelState.IsValid);
            AssertKeysEqual(modelState, "Name", "Profession", "Friend.Name", "Friend.Profession");

            var entry = modelState["Name"];

            Assert.Equal(ModelValidationState.Valid, entry.ValidationState);

            entry = modelState["Profession"];
            Assert.Equal(ModelValidationState.Invalid, entry.ValidationState);
            var error = Assert.Single(entry.Errors);

            Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("Profession"), error.ErrorMessage);

            entry = modelState["Friend.Name"];
            Assert.Equal(ModelValidationState.Invalid, entry.ValidationState);
            error = Assert.Single(entry.Errors);
            Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("Name"), error.ErrorMessage);

            entry = modelState["Friend.Profession"];
            Assert.Equal(ModelValidationState.Invalid, entry.ValidationState);
            error = Assert.Single(entry.Errors);
            Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("Profession"), error.ErrorMessage);
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> LoginPost(LoginViewModel model, string returnUrl = "")
        {
            ViewData["ReturnUrl"] = returnUrl;
            ValidationAttributeUtil.GetRequiredErrorMessage("姓名");
            if (ModelState.IsValid)
            {
                bool succee = (model.UserName == "admin") && (model.Password == "123");

                if (succee)
                {
                    //创建用户身份标识
                    var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                    claimsIdentity.AddClaims(new List <Claim>()
                    {
                        new Claim(ClaimTypes.Sid, model.UserName),
                        new Claim(ClaimTypes.Name, model.UserName),
                        new Claim(ClaimTypes.Role, "admin"),
                        new Claim("LastUpdated", "admin")//当密码有改动时
                    });

                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

                    return(Content("ok"));
                }
                else
                {
                    ModelState.AddModelError("ValidError", "帐号或者密码错误。");
                    StringBuilder strBuild = new StringBuilder();
                    foreach (var item in ModelState.Values)
                    {
                        if (item.Errors.Count > 0)
                        {
                            int itemErrorCount = item.Errors.Count;
                            for (int i = 0; i < itemErrorCount; i++)
                            {
                                strBuild.Append(item.Errors[i].ErrorMessage);
                                strBuild.Append("<br/>");
                            }
                        }
                    }

                    return(Json(strBuild.ToString()));
                }
            }

            return(Json(ModelState));
        }
        public async Task FromBodyAllowingEmptyInputAndRequiredOnProperty_EmptyBody_AddsModelStateError()
        {
            // Arrange
            var parameter = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = "CustomParameter",
                },
                ParameterType = typeof(Person)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                request.Body        = new MemoryStream(Encoding.UTF8.GetBytes(string.Empty));
                request.ContentType = "application/json";
            });

            var modelState = testContext.ModelState;

            var addressRequired = ValidationAttributeUtil.GetRequiredErrorMessage("Address");

            var optionsAccessor = testContext.GetService <IOptions <MvcOptions> >();

            optionsAccessor.Value.AllowEmptyInputInBodyModelBinding = true;

            var parameterBinder = ModelBindingTestHelper.GetParameterBinder(optionsAccessor.Value);

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);
            var boundPerson = Assert.IsType <Person>(modelBindingResult.Model);

            Assert.NotNull(boundPerson);
            var key = Assert.Single(modelState.Keys);

            Assert.Equal("CustomParameter.Address", key);
            Assert.False(modelState.IsValid);
            var error = Assert.Single(modelState[key].Errors);

            Assert.Equal(addressRequired, error.ErrorMessage);
        }
Ejemplo n.º 17
0
        public void CheckBoxFor_WithComplexExpressions_DoesNotUseValuesFromViewDataDictionary()
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
            var expected        =
                $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
                @"id=""HtmlEncode[[ComplexProperty_Property1]]"" name=""HtmlEncode[[ComplexProperty." +
                @"Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[ComplexProperty.Property1]]"" " +
                @"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData());

            // Act
            var html = helper.CheckBoxFor(m => m.ComplexProperty.Property1, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 18
0
        public void CheckBoxForOverridesCalculatedParametersWithValuesFromHtmlAttributes()
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property3");
            var expected        =
                @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
                $@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
                @"id=""HtmlEncode[[Property3]]"" name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[checkbox]]"" " +
                @"value=""HtmlEncode[[false]]"" /><input name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());

            // Act
            var html = helper.CheckBoxFor(m => m.Property3, new { @checked = "checked", value = "false" });

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
        public async Task FromBodyOnTopLevelProperty_RequiredOnSubProperty_AddsModelStateError(string inputText)
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor
            {
                BindingInfo = new BindingInfo
                {
                    BinderModelName = "CustomParameter",
                },
                ParameterType = typeof(Person2),
                Name          = "param-name",
            };

            var testContext = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                request.Body        = new MemoryStream(Encoding.UTF8.GetBytes(inputText));
                request.ContentType = "application/json";
            });
            var httpContext = testContext.HttpContext;
            var modelState  = testContext.ModelState;

            var streetRequired = ValidationAttributeUtil.GetRequiredErrorMessage("Street");

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);
            var boundPerson = Assert.IsType <Person2>(modelBindingResult.Model);

            Assert.NotNull(boundPerson);

            Assert.False(modelState.IsValid);
            var entry = Assert.Single(modelState);

            Assert.Equal("CustomParameter.Address.Street", entry.Key);
            var street = entry.Value;

            Assert.Equal(ModelValidationState.Invalid, street.ValidationState);
            var error = Assert.Single(street.Errors);

            Assert.Equal(streetRequired, error.ErrorMessage);
        }
Ejemplo n.º 20
0
        public void CheckBoxUsesAttemptedValueFromModelState()
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
            var expected        = $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
                                  @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                                  @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";

            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());

            helper.ViewData.ModelState.SetModelValue("Property1", new string[] { "false" }, "false");

            // Act
            var html = helper.CheckBox("Property1", isChecked: null, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 21
0
        public void CheckBoxReplacesUnderscoresInHtmlAttributesWithDashes()
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
            var expected        = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
                                  $@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property1]]"" " +
                                  @"name=""HtmlEncode[[Property1]]"" Property1-Property3=""HtmlEncode[[Property3ObjValue]]"" " +
                                  @"type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " +
                                  @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
            var helper         = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
            var htmlAttributes = new { Property1_Property3 = "Property3ObjValue" };

            // Act
            var html = helper.CheckBox("Property1", isChecked: true, htmlAttributes: htmlAttributes);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 22
0
        public void CheckBoxFor_WithObjectAttribute_MapsUnderscoresInNamesToDashes()
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
            var expected        =
                $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
                @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" " +
                @"Property1-Property3=""HtmlEncode[[Property3ObjValue]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " +
                @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
            var helper         = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
            var htmlAttributes = new { Property1_Property3 = "Property3ObjValue" };

            // Act
            var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
        public async Task ModelMetadataTypeAttribute_InvalidPropertiesOnDerivedClass_HasModelStateErrors()
        {
            // Arrange
            var input = "{ \"Name\": \"MVC\", \"Contact\":\"425-895-9019\", \"Category\":\"Technology\"," +
                        "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 2}";
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BindingSource = BindingSource.Body
                },
                ParameterType = typeof(SoftwareViewModel)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                request.Body        = new MemoryStream(Encoding.UTF8.GetBytes(input));
                request.ContentType = "application/json";
            });

            var modelState = testContext.ModelState;

            var priceRange    = ValidationAttributeUtil.GetRangeErrorMessage(100, 200, "Price");
            var contactLength = ValidationAttributeUtil.GetStringLengthErrorMessage(null, 10, "Contact");

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);
            var boundPerson = Assert.IsType <SoftwareViewModel>(modelBindingResult.Model);

            Assert.NotNull(boundPerson);
            Assert.False(modelState.IsValid);
            var modelStateErrors = CreateValidationDictionary(modelState);

            Assert.Equal(2, modelStateErrors.Count);

            Assert.Equal(priceRange, modelStateErrors["Price"]);
            Assert.Equal(contactLength, modelStateErrors["Contact"]);
        }
Ejemplo n.º 24
0
        public void CheckBoxForWithNullContainer_TreatsBooleanAsFalse()
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
            var expected        =
                $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
                @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
            var viewData = GetTestModelViewData();
            var helper   = DefaultTemplatesUtilities.GetHtmlHelper(viewData);

            viewData.ModelState.SetModelValue("Property1", new string[] { "false" }, "false");

            // Act
            var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
        public void CheckBox_WithHiddenInputRenderModeNone_DoesNotGenerateHiddenInput()
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
            var expected        = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
                                  $@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property1]]"" " +
                                  @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" " +
                                  @"value=""HtmlEncode[[true]]"" />";
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());

            helper.ViewContext.CheckBoxHiddenInputRenderMode = CheckBoxHiddenInputRenderMode.None;

            // Act
            var html = helper.CheckBox("Property1", isChecked: true, htmlAttributes: null);

            // Assert
            Assert.False(helper.ViewContext.FormContext.HasEndOfFormContent);
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 26
0
        public void CheckBoxExplicitParametersOverrideDictionary_ForValueInModel()
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Boolean");
            var expected        = @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
                                  $@"data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Property3]]"" " +
                                  @"name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[checkbox]]"" " +
                                  @"value=""HtmlEncode[[false]]"" /><input name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";

            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());

            // Act
            var html = helper.CheckBox("Property3",
                                       isChecked: true,
                                       htmlAttributes: new { @checked = "unchecked", value = "false" });

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 27
0
        public void Validate_ComplexType_CyclesNotFollowed_Invalid()
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var actionContext     = new ActionContext();
            var modelState        = actionContext.ModelState;
            var validationState   = new ValidationStateDictionary();

            var validator = CreateValidator();

            var person = new Person()
            {
                Name = "Billy"
            };

            person.Friend = person;

            var model = (object)person;

            modelState.SetModelValue("parameter.Name", "Billy", "Billy");
            validationState.Add(model, new ValidationStateEntry()
            {
                Key = "parameter"
            });

            // Act
            validator.Validate(actionContext, validatorProvider, validationState, "parameter", model);

            // Assert
            Assert.False(modelState.IsValid);
            AssertKeysEqual(modelState, "parameter.Name", "parameter.Profession");

            var entry = modelState["parameter.Name"];

            Assert.Equal(ModelValidationState.Valid, entry.ValidationState);
            Assert.Empty(entry.Errors);

            entry = modelState["parameter.Profession"];
            Assert.Equal(ModelValidationState.Invalid, entry.ValidationState);
            var error = Assert.Single(entry.Errors);

            Assert.Equal(error.ErrorMessage, ValidationAttributeUtil.GetRequiredErrorMessage("Profession"));
        }
Ejemplo n.º 28
0
        public void CheckBoxFor_WithAttributeDictionary_GeneratesExpectedAttributes()
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1");
            var expected        =
                $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " +
                @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" " +
                @"Property3=""HtmlEncode[[Property3Value]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " +
                @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
            var helper     = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
            var attributes = new Dictionary <string, object> {
                { "Property3", "Property3Value" }
            };

            // Act
            var html = helper.CheckBoxFor(m => m.Property1, attributes);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
        public async Task CollectionModelBinder_UsesCustomIndexes_AddsErrorsWithCorrectKeys()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name          = "parameter",
                ParameterType = typeof(Person5)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                var formCollection = new FormCollection(new Dictionary <string, StringValues>()
                {
                    { "Addresses.index", new [] { "Key1" } },
                    { "Addresses[Key1].Street", new [] { "Street1" } },
                });

                request.Form        = formCollection;
                request.ContentType = "application/x-www-form-urlencoded";
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);
            Assert.IsType <Person5>(modelBindingResult.Model);

            Assert.False(modelState.IsValid);

            var kvp = Assert.Single(modelState);

            Assert.Equal("Addresses[Key1].Street", kvp.Key);
            var entry = kvp.Value;
            var error = Assert.Single(entry.Errors);

            Assert.Equal(ValidationAttributeUtil.GetStringLengthErrorMessage(null, 3, "Street"), error.ErrorMessage);
        }
Ejemplo n.º 30
0
        public void CheckBoxForGeneratesUnobtrusiveValidationAttributes()
        {
            // Arrange
            var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Name");
            var expected        =
                $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" id=""HtmlEncode[[Name]]""" +
                @" name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                @"<input name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />";
            var metadataProvider   = TestModelMetadataProvider.CreateDefaultProvider();
            var viewDataDictionary = new ViewDataDictionary <ModelWithValidation>(metadataProvider)
            {
                Model = new ModelWithValidation()
            };
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewDataDictionary);

            // Act
            var html = helper.CheckBoxFor(m => m.Name, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }