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)); }
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()); }
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 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); }); }
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"]); }
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"]); }
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)); }
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); }
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); }
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 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)); }
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); }
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)); }
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)); }
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 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)); }
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)); }
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")); }
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 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)); }
public async Task BindPropertyFromHeader_NoData_UsesFullPathAsKeyForModelStateErrors() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "Parameter1", BindingInfo = new BindingInfo() { BinderModelName = "CustomParameter", }, ParameterType = typeof(Person) }; // Do not add any headers. var testContext = ModelBindingTestHelper.GetTestContext(); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert // ModelBindingResult Assert.True(modelBindingResult.IsModelSet); // Model var boundPerson = Assert.IsType <Person>(modelBindingResult.Model); Assert.NotNull(boundPerson); // ModelState Assert.False(modelState.IsValid); var key = Assert.Single(modelState.Keys); Assert.Equal("CustomParameter.Address.Header", key); var error = Assert.Single(modelState[key].Errors); Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("Street"), error.ErrorMessage); }
public async Task ModelMetadataTypeAttribute_InvalidComplexTypePropertyOnBaseClass_HasModelStateErrors() { // Arrange var input = "{ \"Contact\":\"4255678765\", \"Category\":\"Technology\"," + "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 21 }"; 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 productDetailsRequired = ValidationAttributeUtil.GetRequiredErrorMessage("ProductDetails"); // 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(productDetailsRequired, modelStateErrors["ProductDetails"]); }
public void GetClientValidationRules_ReturnsValidationParameters() { // Arrange var expected = ValidationAttributeUtil.GetRequiredErrorMessage("Length"); var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(string), "Length"); var attribute = new RequiredAttribute(); var adapter = new RequiredAttributeAdapter(attribute); var serviceCollection = new ServiceCollection(); var requestServices = serviceCollection.BuildServiceProvider(); var context = new ClientModelValidationContext(metadata, provider, requestServices); // Act var rules = adapter.GetClientValidationRules(context); // Assert var rule = Assert.Single(rules); Assert.Equal("required", rule.ValidationType); Assert.Empty(rule.ValidationParameters); Assert.Equal(expected, rule.ErrorMessage); }
public void CheckBoxFor_UsesModelStateAttemptedValue(string attemptedValue, string expectedChecked) { // Arrange var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1"); 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(); var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData); viewData.ModelState.SetModelValue("Property1", new string[] { attemptedValue }, attemptedValue); // Act var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes: null); // Assert Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html)); }