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


C# ModelStateDictionary.ContainsKey方法代码示例

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


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

示例1: AddExcepition

        public static void AddExcepition(ModelStateDictionary ModelState, Exception ex)
        {
            if (ex is ArgumentException)
            {
                var argEx = (ArgumentException) ex;
                if (!ModelState.ContainsKey(argEx.ParamName)) ModelState.Add(argEx.ParamName, new ModelState());
                var lines = Regex.Split(ex.Message, "\r\n");
                ModelState[argEx.ParamName].Errors.Add(new ModelError(ex, lines[0]));
                return;
            }

            if (!ModelState.ContainsKey("")) ModelState.Add("", new ModelState());

            ModelState[""].Errors.Add(new ModelError(ex, ex.Message));
        }
开发者ID:tendenciaconsult,项目名称:RedivivusProd,代码行数:15,代码来源:Geral.cs

示例2: CopyTempDataToModelState

        private void CopyTempDataToModelState(ModelStateDictionary modelState,
                                              TempDataDictionary tempData)
        {
            if (!tempData.ContainsKey(TempDataKey))
            {
                return;
            }

            ModelStateDictionary fromTempData = tempData[TempDataKey]
                                                    as ModelStateDictionary;
            if (fromTempData == null)
            {
                return;
            }

            foreach (KeyValuePair<string, ModelState> pair in fromTempData)
            {
                if (modelState.ContainsKey(pair.Key))
                {
                    modelState[pair.Key].Value = pair.Value.Value;

                    foreach (ModelError error in pair.Value.Errors)
                    {
                        modelState[pair.Key].Errors.Add(error);
                    }
                }
                else
                {
                    modelState.Add(pair.Key, pair.Value);
                }
            }
        }
开发者ID:stiano,项目名称:ShopperDopper,代码行数:32,代码来源:ModelStateToTempAttribute.cs

示例3: CopyTempDataToModelState

        private void CopyTempDataToModelState(ModelStateDictionary modelState, TempDataDictionary tempData)
        {
            if (!tempData.ContainsKey(TempDataKey)) return;

            var fromTempData = tempData[TempDataKey] as ModelStateDictionary;
            if (fromTempData == null) return;

            foreach (var pair in fromTempData)
            {
                if (modelState.ContainsKey(pair.Key))
                {
                    modelState[pair.Key].Value = pair.Value.Value;

                    foreach (var error in pair.Value.Errors)
                    {
                        if (!modelState[pair.Key].Errors.Contains(error))
                            modelState[pair.Key].Errors.Add(error);
                    }
                }
                else
                {
                    modelState.Add(pair.Key, pair.Value);
                }
            }
        }
开发者ID:kenwarner,项目名称:scrilla,代码行数:25,代码来源:Attributes.cs

示例4: GetProgressPercentage

        /// <summary>
        /// Used to calculate Model filling status in percentage
        /// </summary>
        /// <param name="modelState">Model state that contains information about filled fields</param>
        /// <param name="prefix">Prefix that used to get full path to elemet returned from page</param>
        public int GetProgressPercentage(ModelStateDictionary modelState, string prefix)
        {
            var successCnt = 0;
            var errorCnt = 0;

            var formattedList = this.GetAllPropertyFormattedList(this).Select(s => prefix + s).ToList();

            foreach (var element in formattedList)
            {
                if (modelState.ContainsKey(element))
                {
                    if (modelState[element].Errors.Count == 0)
                    {
                        if (!string.IsNullOrEmpty(modelState[element].Value.AttemptedValue))
                        {
                            successCnt++;
                        }
                    }
                    else
                    {
                        errorCnt++;
                    }
                }
            }

            var totalCnt = successCnt + errorCnt;

            return totalCnt == 0 ? 100 : (successCnt * 100 / totalCnt);
        }
开发者ID:targitaj,项目名称:m3utonetpaleyerxml,代码行数:34,代码来源:BaseModel.cs

示例5: HasErrors

 public static void HasErrors(ModelStateDictionary dict, string key, params ModelError[] errors)
 {
     Assert.True(dict.ContainsKey(key));
     var state = dict[key];
     Assert.Equal(
         // Tuples have an Equals override. ModelError doesn't :(
         errors.Select(e => Tuple.Create(e.Exception, e.ErrorMessage)).ToArray(),
         state.Errors.Select(e => Tuple.Create(e.Exception, e.ErrorMessage)).ToArray());
 }
开发者ID:henrycomein,项目名称:NuGetGallery,代码行数:9,代码来源:ModelStateAssert.cs

示例6: ShouldCopyAllErrorsWithPrefix

        public void ShouldCopyAllErrorsWithPrefix()
        {
            // arrange
            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("Email", "Invalid");
            nvc.Add("Email", "Mising");
            nvc.Add("Password", "Mising");

            ValidationException ex = new ValidationException { Errors = nvc };
            ModelStateDictionary modelState = new ModelStateDictionary();

            // act
            ex.ToModelErrors(modelState, "credentials");

            // assert
            Assert.IsFalse(modelState.ContainsKey("Email"));
            Assert.IsFalse(modelState.ContainsKey("Password"));
            Assert.AreEqual(2, modelState["credentials.Email"].Errors.Count);
            Assert.AreEqual(1, modelState["credentials.Password"].Errors.Count);
        }
开发者ID:triggerfish,项目名称:Common,代码行数:20,代码来源:ValidationExtensionsTests.cs

示例7: LogErrorAddsErrorToModelState

        public void LogErrorAddsErrorToModelState()
        {
            ModelStateDictionary modelState = new ModelStateDictionary();
            string prefix = "prefix";
            IFormatterLogger formatterLogger = new ModelStateFormatterLogger(modelState, prefix);

            formatterLogger.LogError("property", "error");

            Assert.True(modelState.ContainsKey("prefix.property"));
            Assert.Equal(1, modelState["prefix.property"].Errors.Count);
            Assert.Equal("error", modelState["prefix.property"].Errors[0].ErrorMessage);
        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:12,代码来源:ModelStateFormatterLoggerTest.cs

示例8: ReadAsync_UsesTryAddModelValidationErrorsToModelState

        public async Task ReadAsync_UsesTryAddModelValidationErrorsToModelState()
        {
            // Arrange
            var content = "{name: 'Person Name', Age: 'not-an-age'}";
            var logger = GetLogger();
            var formatter =
                new JsonInputFormatter(logger, _serializerSettings, ArrayPool<char>.Shared, _objectPoolProvider);
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes);
            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForType(typeof(User));
            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                metadata: metadata,
                readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);

            modelState.MaxAllowedErrors = 3;
            modelState.AddModelError("key1", "error1");
            modelState.AddModelError("key2", "error2");

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.True(result.HasError);
            Assert.False(modelState.ContainsKey("age"));
            var error = Assert.Single(modelState[""].Errors);
            Assert.IsType<TooManyModelErrorsException>(error.Exception);
        }
开发者ID:ymd1223,项目名称:Mvc,代码行数:33,代码来源:JsonInputFormatterTest.cs

示例9: MergeDoesNothingIfParameterIsNull

        public void MergeDoesNothingIfParameterIsNull()
        {
            // Arrange
            var dictionary = new ModelStateDictionary() { { "foo", new ModelStateEntry() } };

            // Act
            dictionary.Merge(null);

            // Assert
            Assert.Single(dictionary);
            Assert.True(dictionary.ContainsKey("foo"));
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:12,代码来源:ModelStateDictionaryTest.cs

示例10: ContainsKey_ReturnsTrue_IfNodeHasBeenMutated

        public void ContainsKey_ReturnsTrue_IfNodeHasBeenMutated(string key)
        {
            // Arrange
            var dictionary = new ModelStateDictionary();
            dictionary.MarkFieldSkipped(key);

            // Act
            var result = dictionary.ContainsKey(key);

            // Assert
            Assert.True(result);
        }
开发者ID:ymd1223,项目名称:Mvc,代码行数:12,代码来源:ModelStateDictionaryTest.cs

示例11: IsPasswordValidFalse

		public void IsPasswordValidFalse()
		{
			var service = GetMockedUserService();
			var modelState = new ModelStateDictionary();
			var result = service.IsPasswordValid("12345", modelState);
			Assert.False(result);
			Assert.AreEqual(1, modelState.Count);
			Assert.True(modelState.ContainsKey("Password"));
		}
开发者ID:andyliyuze,项目名称:POPForums,代码行数:9,代码来源:UserServiceTests.cs

示例12: SetLogo

        private void SetLogo(EditEventViewModel viewModel, ModelStateDictionary modelState)
        {
            bool hasLogo = Session[CurrentLogoKey] != null;

            if(hasLogo)
            {
                viewModel.Logo = (byte[])Session[CurrentLogoKey];
                viewModel.IsLogoSetted = true;
                viewModel.HasLogo = true;
                if(modelState.ContainsKey("HasLogo"))
                    modelState.Remove("HasLogo");
            }
        }
开发者ID:garymedina,项目名称:MyEvents,代码行数:13,代码来源:EventController.cs

示例13: Should_add_to_modelstate_without_prefix

    	public void Should_add_to_modelstate_without_prefix()
    	{
			var thing = new Thing();
			var form = new FormCollection 
			{
				{ "Age", "not a number" }
			};

			var modelState = new ModelStateDictionary();
			try 
			{
				validatingBinder.UpdateFrom(thing, form, modelState);
			}
			catch {}
			finally 
			{
				modelState.ContainsKey("Age").ShouldBeTrue();
			}
    	}
开发者ID:bertusmagnus,项目名称:Sutekishop,代码行数:19,代码来源:ValidatingBinderTests.cs

示例14: CreateUser_would_report_error_if_the_creator_has_no_rights

        public void CreateUser_would_report_error_if_the_creator_has_no_rights()
        {
            SetUpEmptyUserExpectationForCreateNewAccountWithValidConditions();

            var modelError = new ModelStateDictionary();
            _userAuthenticationServiceSUT.Create(null, _nonExistignUserName, modelError);

            Assert.True(modelError.ContainsKey(string.Empty));
            Assert.True(modelError.ContainsError(string.Empty, AccountString.CreatorLackOfRight));
        }
开发者ID:JohnCai,项目名称:agilewizard,代码行数:10,代码来源:UserAuthenticationServiceTest.cs

示例15: NullCheckFailedHandler_ModelStateAlreadyInvalid_DoesNothing

        public void NullCheckFailedHandler_ModelStateAlreadyInvalid_DoesNothing()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.AddModelError("foo.bar", "Some existing error.");

            var modelMetadata = GetMetadataForType(typeof(Person));
            var validationNode = new ModelValidationNode(modelMetadata, "foo");
            var validationContext = new ModelValidationContext(new DataAnnotationsModelMetadataProvider(),
                                                               Enumerable.Empty<IModelValidatorProvider>(),
                                                               modelState,
                                                               modelMetadata,
                                                               null);
            var e = new ModelValidatedEventArgs(validationContext, parentNode: null);

            // Act
            var handler = MutableObjectModelBinder.CreateNullCheckFailedHandler(modelMetadata, incomingValue: null);
            handler(validationNode, e);

            // Assert
            Assert.False(modelState.ContainsKey("foo"));
        }
开发者ID:Nakro,项目名称:Mvc,代码行数:22,代码来源:MutableObjectModelBinderTest.cs


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