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


C# ModelStateDictionary类代码示例

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


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

示例1: KeyValuePairModelBinder_SimpleTypes_WithNoKey_AddsError

        public async Task KeyValuePairModelBinder_SimpleTypes_WithNoKey_AddsError()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter = new ParameterDescriptor
            {
                Name = "parameter",
                ParameterType = typeof(KeyValuePair<string, int>)
            };
            var operationContext = ModelBindingTestHelper.GetOperationBindingContext(request =>
            {
                request.QueryString = new QueryString("?parameter.Value=10");
            });
            var modelState = new ModelStateDictionary();

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, modelState, operationContext);

            // Assert
            Assert.False(modelBindingResult.IsModelSet);
            Assert.Equal(2, modelState.Count);

            Assert.False(modelState.IsValid);
            Assert.Equal(1, modelState.ErrorCount);

            var entry = Assert.Single(modelState, kvp => kvp.Key == "parameter.Key").Value;
            var error = Assert.Single(entry.Errors);
            Assert.Null(error.Exception);
            Assert.Equal("A value is required.", error.ErrorMessage);

            entry = Assert.Single(modelState, kvp => kvp.Key == "parameter.Value").Value;
            Assert.Empty(entry.Errors);
            Assert.Equal("10", entry.AttemptedValue);
            Assert.Equal("10", entry.RawValue);
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:35,代码来源:KeyValuePairModelBinderIntegrationTest.cs

示例2: ModelStateException

        public ModelStateException(ModelStateDictionary modelState)
        {
            if (modelState == null)
            {
                throw new ArgumentNullException("modelState");
            }

            Errors = new Dictionary<string, string>();

            if (!modelState.IsValid)
            {
                StringBuilder errors;
                foreach (KeyValuePair<string, ModelState> state in modelState)
                {
                    if (state.Value.Errors.Count > 0)
                    {
                        errors = new StringBuilder();
                        foreach (ModelError err in state.Value.Errors)
                        {
                            errors.AppendLine(err.ErrorMessage);
                        }
                        Errors.Add(state.Key, errors.ToString());
                    }
                }
            }
        }
开发者ID:kev1awlor,项目名称:Timetracker,代码行数:26,代码来源:ModelStateException.cs

示例3: AddErrorsToModelState

		internal void AddErrorsToModelState(IEnumerable<DbEntityValidationResult> errors, ModelStateDictionary state)
		{
			foreach (var val in errors)
			{
				AddErrorsToModelState(val, state);
			}
		}
开发者ID:jcanady20,项目名称:Scheduler.Service,代码行数:7,代码来源:BaseApiController.cs

示例4: 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

示例5: MapBrokenRules

 public static void MapBrokenRules(ModelStateDictionary modelState, Csla.Core.BusinessBase businessObject)
 {
     foreach (var brokenRule in businessObject.BrokenRulesCollection)
     {
         modelState.AddModelError(brokenRule.Property, brokenRule.Description);
     }
 }
开发者ID:mattruma,项目名称:epiworx-csla,代码行数:7,代码来源:ModelHelper.cs

示例6: BindParameter_WithModelBinderType_NoData_ReturnsNull

        public async Task BindParameter_WithModelBinderType_NoData_ReturnsNull()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter = new ParameterDescriptor()
            {
                Name = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BinderType = typeof(NullModelNotSetModelBinder)
                },

                ParameterType = typeof(string)
            };

            // No data is passed.
            var operationContext = ModelBindingTestHelper.GetOperationBindingContext();
            var modelState = new ModelStateDictionary();

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, modelState, operationContext);

            // Assert

            // ModelBindingResult
            Assert.Null(modelBindingResult);

            // ModelState (not set unless inner binder sets it)
            Assert.True(modelState.IsValid);
            Assert.Empty(modelState);
        }
开发者ID:njannink,项目名称:sonarlint-vs,代码行数:31,代码来源:BinderTypeBasedModelBinderIntegrationTest.cs

示例7: InvalidModelStateResult_WritesHttpError

        public async Task InvalidModelStateResult_WritesHttpError()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            httpContext.RequestServices = CreateServices();

            var stream = new MemoryStream();
            httpContext.Response.Body = stream;

            var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            var modelState = new ModelStateDictionary();
            modelState.AddModelError("product.Name", "Name is required.");

            var expected =
                "{\"Message\":\"The request is invalid.\"," +
                "\"ModelState\":{\"product.Name\":[\"Name is required.\"]}}";

            var result = new InvalidModelStateResult(modelState, includeErrorDetail: false);

            // Act
            await result.ExecuteResultAsync(context);

            // Assert
            using (var reader = new StreamReader(stream))
            {
                stream.Seek(0, SeekOrigin.Begin);
                var content = reader.ReadToEnd();
                Assert.Equal(expected, content);
            }
        }
开发者ID:phinq19,项目名称:git_example,代码行数:31,代码来源:InvalidModelStateResultTest.cs

示例8: JsonData

        public JsonData(ModelStateDictionary modelDic)
            : this()
        {
            List<string> errorList = new List<string>();
            List<string> keyList = new List<string>();
            List<int> errorIndexList = new List<int>();

            int i = 0;
            foreach (ModelState state in modelDic.Values) {
                if (state.Errors.Count > 0) {
                    string error = state.Errors[0].ErrorMessage;
                    errorList.Add(error);
                    errorIndexList.Add(i);
                }
                i++;
            }

            int j = 0;
            foreach (string key in modelDic.Keys) {
                if (errorIndexList.Any(x => x == j)) {
                    keyList.Add(key.Replace(".", "_"));
                }
                j++;
            }

            for (int x = 0; x <= errorList.Count - 1; x++) {
                ErrorList.Add(new FormFiledError(keyList[x], errorList[x]));
            }

            if (errorList.Count > 0) this.HasFormError = true;
        }
开发者ID:qiuliang,项目名称:IVV,代码行数:31,代码来源:JsonData.cs

示例9: ShouldCopyToModelState

		public void ShouldCopyToModelState()
		{
			var modelstate = new ModelStateDictionary();

			const string property = "";

			var validator = new Validator
            {
            	() => property.Label("Property 1").IsRequired(),
            	() => property.Label("Property 2").IsRequired(),
            	() => property.Label("Property 3").IsRequired()
            };

			try
			{
				validator.Validate();
			}
			catch (ValidationException ex)
			{
				ex.CopyToModelState(modelstate, "foo");
			}

			modelstate.Count.ShouldEqual(3);
			modelstate["foo.Property 1"].ShouldNotBeNull();
			modelstate["foo.Property 2"].ShouldNotBeNull();
			modelstate["foo.Property 3"].ShouldNotBeNull();

		}
开发者ID:bertusmagnus,项目名称:Sutekishop,代码行数:28,代码来源:ValidationExtensionsTests.cs

示例10: Update

        public bool Update(UsersExt model, ModelStateDictionary modelState, Controller ctrl)
        {
            bool status = true;
            //Wrap it all in a transaction
            TransactionOptions transOptions = SetTransactionTimeoutForDebugging(HttpContext.Current);

            using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required, transOptions))
            {
                //if (db.tblUsers.Any(u => u.UserID != model.UserID && u.Username.ToLower().Equals(model.Username)))
                //{
                //    status = false;
                //    modelState.AddModelError("Username", "Username already Exists.");
                //}
                //else
                //{
                //    //TODO: Map to DB Object
                //    tblUsers tbluser = Map(model);

                //    tbluser.Password = SecurityUtils.EncryptText(tbluser.Password);

                //    db.tblUsers.Attach(tbluser);
                //    db.Entry(tbluser).State = System.Data.Entity.EntityState.Modified;
                //    db.SaveChanges();

                //    //TOD: Add to Audit Log
                //    SecurityUtils.AddAuditLog("User Details has been Updated. User FullName = " + model.Fullname, ctrl);

                //    //To get here, everything must be OK, so commit the transaction
                //    transaction.Complete();
                //}
            }

            return status;
        }
开发者ID:tomasroy2015,项目名称:gbs-angular-html5,代码行数:34,代码来源:UsersRepository.cs

示例11: Delete

 public virtual void Delete(SysEventViewModel sys, ModelStateDictionary modelState)
 {
     var entity = sys.ToEntity();
     db.SysEvents.Attach(entity);
     db.SysEvents.Remove(entity);
     db.SaveChanges();
 }
开发者ID:nhuang,项目名称:fvs,代码行数:7,代码来源:SysEventService.cs

示例12: Create

        public bool Create(UsersExt model, ModelStateDictionary modelState, Controller ctrl)
        {
            bool status = true;
            //Wrap it all in a transaction

            TransactionOptions transOptions = SetTransactionTimeoutForDebugging(HttpContext.Current);

            using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required, transOptions))
            {
                //if (db.tblUsers.Any(u => u.Username.ToLower().Equals(model.Username)))
                //{
                //    status = false;
                //    modelState.AddModelError("Username", "Username already Exists.");

                //}
                //else
                //{

                //    tblUsers tbluser = Map(model);

                //    tbluser.Password = SecurityUtils.EncryptText(tbluser.Password);

                //    db.tblUsers.Add(tbluser);
                //    db.SaveChanges();

                //    // UserID = tbluser.UserID;
                //    //Add to Audit Log
                //    SecurityUtils.AddAuditLog("User has been Added. User FullName = " + model.Fullname, ctrl);
                //    transaction.Complete();
                //}
            }
            return status;
        }
开发者ID:tomasroy2015,项目名称:gbs-angular-html5,代码行数:33,代码来源:UsersRepository.cs

示例13: ModelStateToString

        public static string ModelStateToString(ModelStateDictionary modelState)
        {
            Contract.Assert(modelState != null);

            if (modelState.IsValid)
            {
                return String.Empty;
            }

            StringBuilder modelStateBuilder = new StringBuilder();
            foreach (string key in modelState.Keys)
            {
                ModelState state = modelState[key];
                if (state.Errors.Count > 0)
                {
                    foreach (ModelError error in state.Errors)
                    {
                        string errorString = Error.Format(SRResources.TraceModelStateErrorMessage, 
                                                           key,
                                                           error.ErrorMessage);
                        if (modelStateBuilder.Length > 0)
                        {
                            modelStateBuilder.Append(',');
                        }

                        modelStateBuilder.Append(errorString);
                    }
                }
            }

            return modelStateBuilder.ToString();
        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:32,代码来源:FormattingUtilities.cs

示例14: ValidateModelForNew

        public void ValidateModelForNew(ModelStateDictionary modelstate, int i)
        {
            modelState = modelstate;
            Index = i;
            IsValidForNew = true; // Assume true until proven false
            IsValidForContinue = true; // Assume true until proven false

            ValidateBasic();
            ValidateBirthdate();
            if (!IsValidForNew)
                return;
            ValidateBirthdayRange(selectFromFamily: false);
            ValidatePhone();
            ValidateEmailForNew();
            if (!CanProceedWithThisAddress())
            {
                IsValidForContinue = false;
                return;
            }
            ValidateCampus();
            ValidateGender();
            ValidateMarital();
            ValidateMembership();
            IsValidForContinue = IsValidForNew = modelState.IsValid;
        }
开发者ID:stevesloka,项目名称:bvcms,代码行数:25,代码来源:ValidateModelForNew.cs

示例15: Validate

        public void Validate(ModelStateDictionary mdlState)
        {
            base.Validate();

            foreach (var tags in _nameTags)
            {
                var error = tags.Value.ValidationError;
                if (error != null)
                {
                    var strError = string.Join(", ", error.Errors);
                    if (!string.IsNullOrWhiteSpace(strError))
                    {
                        if (tags.Value is DataObjectViewModel)
                        {
                            // Special case DatObject: remove any key
                            mdlState.AddModelError("", strError);
                        }
                        else
                        {
                            mdlState.AddModelError(tags.Key, strError);
                        }
                    }
                }
            }
        }
开发者ID:daszat,项目名称:zetbox,代码行数:25,代码来源:MVCValidationManager.cs


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