当前位置: 首页>>代码示例>>C#>>正文


C# ModelStateDictionary.SetModelValue方法代码示例

本文整理汇总了C#中ModelStateDictionary.SetModelValue方法的典型用法代码示例。如果您正苦于以下问题:C# ModelStateDictionary.SetModelValue方法的具体用法?C# ModelStateDictionary.SetModelValue怎么用?C# ModelStateDictionary.SetModelValue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ModelStateDictionary的用法示例。


在下文中一共展示了ModelStateDictionary.SetModelValue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Validate_SimpleType_MaxErrorsReached

        public void Validate_SimpleType_MaxErrorsReached()
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var modelState = new ModelStateDictionary();
            var validationState = new ValidationStateDictionary();

            var validator = CreateValidator();

            var model = (object)"test";

            modelState.MaxAllowedErrors = 1;
            modelState.AddModelError("other.Model", "error");
            modelState.SetModelValue("parameter", "test", "test");
            validationState.Add(model, new ValidationStateEntry() { Key = "parameter" });

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

            // Assert
            Assert.False(modelState.IsValid);
            AssertKeysEqual(modelState, string.Empty, "parameter");

            var entry = modelState["parameter"];
            Assert.Equal(ModelValidationState.Skipped, entry.ValidationState);
            Assert.Empty(entry.Errors);
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:27,代码来源:DefaultObjectValidatorTests.cs

示例2: Validate_SimpleReferenceType_Valid_WithPrefix

        public void Validate_SimpleReferenceType_Valid_WithPrefix()
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var modelState = new ModelStateDictionary();
            var validationState = new ValidationStateDictionary();

            var validator = CreateValidator();

            var model = (object)"test";

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

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

            // Assert
            Assert.True(modelState.IsValid);
            AssertKeysEqual(modelState, "parameter");

            var entry = modelState["parameter"];
            Assert.Equal(ModelValidationState.Valid, entry.ValidationState);
            Assert.Empty(entry.Errors);
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:25,代码来源:DefaultObjectValidatorTests.cs

示例3: AddToModelState

		/// <summary>
		/// Stores the errors in a ValidationResult object to the specified modelstate dictionary.
		/// </summary>
		/// <param name="result">The validation result to store</param>
		/// <param name="modelState">The ModelStateDictionary to store the errors in.</param>
		/// <param name="prefix">An optional prefix. If ommitted, the property names will be the keys. If specified, the prefix will be concatenatd to the property name with a period. Eg "user.Name"</param>
		public static void AddToModelState(this ValidationResult result, ModelStateDictionary modelState, string prefix) {
			if (!result.IsValid) {
				foreach (var error in result.Errors) {
					string key = string.IsNullOrEmpty(prefix) ? error.PropertyName : prefix + "." + error.PropertyName;
					modelState.AddModelError(key, error.ErrorMessage);
					//To work around an issue with MVC: SetModelValue must be called if AddModelError is called.
					modelState.SetModelValue(key, new ValueProviderResult(error.AttemptedValue ?? "", (error.AttemptedValue ?? "").ToString(), CultureInfo.CurrentCulture));
				}
			}
		}
开发者ID:grammarware,项目名称:fodder,代码行数:16,代码来源:src_ServiceStack_FluentValidation_Mvc3_ValidationResultExtension.cs

示例4: TextAreaWithObjectAttributes

        public void TextAreaWithObjectAttributes() {
            // Arrange
            ModelStateDictionary modelState = new ModelStateDictionary();
            modelState.SetModelValue("foo", "foo-value");
            HtmlHelper helper = new HtmlHelper(modelState);

            // Act
            var html = helper.TextArea("foo", new { attr = "value", cols = 6 });

            // Assert
            Assert.AreEqual(@"<textarea attr=""value"" cols=""6"" id=""foo"" name=""foo"" rows=""2"">foo-value</textarea>", html.ToHtmlString());
        }
开发者ID:jesshaw,项目名称:ASP.NET-Mvc-3,代码行数:12,代码来源:TextAreaHelperTest.cs

示例5: RadioButtonUsesModelStateToRemoveChecked

        public void RadioButtonUsesModelStateToRemoveChecked() {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.SetModelValue("foo", "not-a-bar");
            HtmlHelper helper = new HtmlHelper(modelState);

            // Act
            var html = helper.RadioButton("foo", "bar", new { @checked = "checked" } );

            // Assert
            Assert.AreEqual(@"<input id=""foo"" name=""foo"" type=""radio"" value=""bar"" />",
                html.ToHtmlString());
        }
开发者ID:adrianvallejo,项目名称:MVC3_Source,代码行数:13,代码来源:RadioButtonTest.cs

示例6: CheckboxWithModelValue

        public void CheckboxWithModelValue() {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.SetModelValue("foo", true);
            HtmlHelper helper = new HtmlHelper(modelState);

            // Act
            var html = helper.CheckBox("foo");

            // Assert
            Assert.AreEqual(@"<input checked=""checked"" id=""foo"" name=""foo"" type=""checkbox"" />",
                html.ToHtmlString());
        }
开发者ID:jesshaw,项目名称:ASP.NET-Mvc-3,代码行数:13,代码来源:CheckBoxTest.cs

示例7: TextAreaWithExplicitValue

        public void TextAreaWithExplicitValue()
        {
            // Arrange
            ModelStateDictionary modelState = new ModelStateDictionary();
            modelState.SetModelValue("foo", "explicit-foo-value");
            HtmlHelper helper = HtmlHelperFactory.Create(modelState);

            // Act
            var html = helper.TextArea("foo", "explicit-foo-value", new { attr = "attr-value", cols = 6 });

            // Assert
            Assert.Equal(@"<textarea attr=""attr-value"" cols=""6"" id=""foo"" name=""foo"" rows=""2"">explicit-foo-value</textarea>",
                         html.ToHtmlString());
        }
开发者ID:marojeri,项目名称:aspnetwebstack,代码行数:14,代码来源:TextAreaHelperTest.cs

示例8: RadioButtonUsesModelStateToAssignChecked

        public void RadioButtonUsesModelStateToAssignChecked()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.SetModelValue("foo", "bar");
            HtmlHelper helper = HtmlHelperFactory.Create(modelState);

            // Act
            var html = helper.RadioButton("foo", "bar");

            // Assert
            Assert.Equal(@"<input checked=""checked"" id=""foo"" name=""foo"" type=""radio"" value=""bar"" />",
                         html.ToHtmlString());
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:14,代码来源:RadioButtonTest.cs

示例9: DeserialiseModelState

        protected ModelStateDictionary DeserialiseModelState(string serialisedErrors)
        {
            var modelState = new ModelStateDictionary();
            var entries = JsonConvert.DeserializeObject<IList<ModelStateTransferEntry>>(serialisedErrors, JsonSettings);

            foreach (var entry in entries)
            {
                modelState.SetModelValue(entry.Key, entry.RawValue, entry.AttemptedValue);

                foreach (var error in entry.ErrorMessages)
                {
                    modelState.AddModelError(entry.Key, error);
                }
            }

            return modelState;
        }
开发者ID:ankn85,项目名称:apex,代码行数:17,代码来源:ModelStateTransfer.cs

示例10: TransferValidationMessagesTo

        /// <summary>
        /// This acts as a more "manual" alternative to moving validation errors to the 
        /// <see cref="ModelStateDictionary" /> if you care to bypass the use of 
        /// <see cref="ValidatableModelBinder" />.  This typically wouldn't be used in conjunction
        /// with <see cref="ValidatableModelBinder" /> but as an alternative to it.
        /// </summary>
        /// <param name="keyBase">If supplied, will be used as the model state prefix
        /// instead of the class name</param>
        public static ModelStateDictionary TransferValidationMessagesTo(
            string keyBase, ModelStateDictionary modelStateDictionary, 
            IEnumerable<IValidationResult> validationResults)
        {
            Check.Require(modelStateDictionary != null, "modelStateDictionary may not be null");
            Check.Require(validationResults != null, "invalidValues may not be null");

            foreach (IValidationResult validationResult in validationResults) {
                Check.Require(validationResult.ClassContext != null,
                    "validationResult.ClassContext may not be null");

                string key = (keyBase ?? validationResult.ClassContext.Name) +
                    (!string.IsNullOrEmpty(validationResult.PropertyName)
                        ? "." + validationResult.PropertyName
                        : "");

                modelStateDictionary.AddModelError(key, validationResult.Message);
                modelStateDictionary.SetModelValue(key, new ValueProviderResult(null, null, null));
            }

            return modelStateDictionary;
        }
开发者ID:kythorn,项目名称:Sharp-Architecture,代码行数:30,代码来源:MvcValidationAdapter.cs

示例11: TransferValidationMessagesTo

        /// <summary>
        /// This acts as a more "manual" alternative to moving validation errors to the 
        /// <see cref="ModelStateDictionary" /> if you care to bypass the use of 
        /// <see cref="ValidatableModelBinder" />.  This typically wouldn't be used in conjunction
        /// with <see cref="ValidatableModelBinder" /> but as an alternative to it.
        /// </summary>
        /// <param name="keyBase">If supplied, will be used as the model state prefix
        /// instead of the class name</param>
        public static ModelStateDictionary TransferValidationMessagesTo(
            string keyBase, ModelStateDictionary modelStateDictionary, 
            IEnumerable<IValidationResult> validationResults)
        {
            Check.Require(modelStateDictionary != null, "modelStateDictionary may not be null");
            Check.Require(validationResults != null, "invalidValues may not be null");

            foreach (IValidationResult validationResult in validationResults) {
                Check.Require(validationResult.ClassContext != null,
                    "validationResult.ClassContext may not be null");

                string key = (keyBase ?? validationResult.ClassContext.Name) +
                    (!string.IsNullOrEmpty(validationResult.PropertyName)
                        ? "." + validationResult.PropertyName
                        : "");
                key = key.Trim('.'); //fixes issue where key ends up as .PropertyName instead of object.PropertyName or just PropertyName
                modelStateDictionary.AddModelError(key, validationResult.Message);
                modelStateDictionary.SetModelValue(key, new ValueProviderResult(validationResult.AttemptedValue ?? "", (validationResult.AttemptedValue ?? "").ToString(), CultureInfo.CurrentCulture)); //Fixes problem where invalid fields get blanked out.
                //modelStateDictionary.SetModelValue(key, new ValueProviderResult(null, null, null));
            }

            return modelStateDictionary;
        }
开发者ID:sztupy,项目名称:shaml,代码行数:31,代码来源:MvcValidationAdapter.cs

示例12: SetAttemptedValueUsesExistingModelStateIfPresent

        public void SetAttemptedValueUsesExistingModelStateIfPresent()
        {
            // Arrange
            ModelStateDictionary dictionary = new ModelStateDictionary();
            dictionary.AddModelError("some key", "some error");
            Exception ex = new Exception();

            // Act
            dictionary.SetModelValue("some key", HtmlHelperTest.GetValueProviderResult("some value", "some value"));

            // Assert
            Assert.Single(dictionary);
            ModelState modelState = dictionary["some key"];

            Assert.Single(modelState.Errors);
            Assert.Equal("some error", modelState.Errors[0].ErrorMessage);
            Assert.Equal("some value", modelState.Value.ConvertTo(typeof(string)));
        }
开发者ID:huangw-t,项目名称:aspnetwebstack,代码行数:18,代码来源:ModelStateDictionaryTest.cs

示例13: Validate_ComplexType_CyclesNotFollowed_Invalid

        public void Validate_ComplexType_CyclesNotFollowed_Invalid()
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var modelState = new ModelStateDictionary();
            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(validatorProvider, modelState, 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"));
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:33,代码来源:DefaultObjectValidatorTests.cs

示例14: Validate_ForExcludedType_PropertiesMarkedAsSkipped

        public void Validate_ForExcludedType_PropertiesMarkedAsSkipped()
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var modelState = new ModelStateDictionary();
            var validationState = new ValidationStateDictionary();

            var validator = CreateValidator(typeof(User));

            var model = new User()
            {
                Password = "password-val",
                ConfirmPassword = "not-password-val"
            };

            // Note that user.ConfirmPassword has no entry in modelstate - we should not
            // create one just to mark it as skipped.
            modelState.SetModelValue("user.Password", "password-val", "password-val");
            validationState.Add(model, new ValidationStateEntry() { Key = "user", });

            // Act
            validator.Validate(validatorProvider, modelState, validationState, "user", model);

            // Assert
            Assert.Equal(ModelValidationState.Valid, modelState.ValidationState);
            AssertKeysEqual(modelState, "user.Password");

            var entry = modelState["user.Password"];
            Assert.Equal(ModelValidationState.Skipped, entry.ValidationState);
            Assert.Empty(entry.Errors);
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:31,代码来源:DefaultObjectValidatorTests.cs

示例15: RadioButtonWithNonStringValue

        public void RadioButtonWithNonStringValue()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.SetModelValue("foo", "bar");
            HtmlHelper helper = HtmlHelperFactory.Create(modelState);

            // Act
            var html = helper.RadioButton("foo", 2.53);

            // Assert
            Assert.Equal(@"<input id=""foo"" name=""foo"" type=""radio"" value=""2.53"" />",
                         html.ToHtmlString());
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:14,代码来源:RadioButtonTest.cs


注:本文中的ModelStateDictionary.SetModelValue方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。