• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ModelStateDictionary类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: SendEmails

        public ModelStateDictionary SendEmails(DefaultContext db)
        {
            var modelStateDictionary = new ModelStateDictionary();
            UserProfile[] userProfiles = UserProfileCache.GetIndex(db);
            bool success = true;
            foreach (UserProfile userProfile in userProfiles.Where(up => !String.IsNullOrEmpty(up.Email1)))
            {
                bool partialSuccess = Mail.SendEmail(userProfile.Email1, Subject, Body, true, true);
                if (partialSuccess)
                {
                    string logMessage = String.Format("Email for user {0} with address {1} was successfully sent.", userProfile.FullName, userProfile.Email1);
                    Logger.SetLog(logMessage);
                }
                else
                {
                    string errorMessage = String.Format("Email for user {0} with address {1} was not sent.", userProfile.FullName, userProfile.Email1);
                    Logger.SetErrorLog(errorMessage);
                }

                success &= partialSuccess;
            }

            if (!success)
            {
                modelStateDictionary.AddModelError(BaseCache.EmptyField, ValidationResource.BulkMail_SomeEmailWasNotSent_ErrorMessage);
            }

            return modelStateDictionary;
        }
开发者ID:MulderFox,项目名称:Main,代码行数:29,代码来源:BulkMailModelView.cs


示例17: Create

 internal static HtmlHelper Create(ModelStateDictionary modelStateDictionary = null, ValidationHelper validationHelper = null)
 {
     modelStateDictionary = modelStateDictionary ?? new ModelStateDictionary();
     var httpContext = new Mock<HttpContextBase>();
     validationHelper = validationHelper ?? new ValidationHelper(httpContext.Object, modelStateDictionary);
     return new HtmlHelper(modelStateDictionary, validationHelper);
 }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:7,代码来源:HtmlHelperFactory.cs


示例18: GetErrorList

 public static List<string> GetErrorList(ModelStateDictionary modelState)
 {
     var errorList = from state in modelState.Values
                     from error in state.Errors
                     select error.ErrorMessage;
     return errorList.ToList();
 }
开发者ID:theroadisnear,项目名称:themonitoringisnear,代码行数:7,代码来源:CustomValidationMessage.cs


示例19: GenericModelBinder_BindsCollection_ElementTypeFromGreedyModelBinder_EmptyPrefix_Success

        public async Task GenericModelBinder_BindsCollection_ElementTypeFromGreedyModelBinder_EmptyPrefix_Success()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter = new ParameterDescriptor()
            {
                Name = "parameter",
                ParameterType = typeof(List<IFormCollection>)
            };
            // Need to have a key here so that the GenericModelBinder will recurse to bind elements.
            var operationContext = ModelBindingTestHelper.GetOperationBindingContext(request =>
            {
                request.QueryString = new QueryString("?index=10");
            });

            var modelState = new ModelStateDictionary();

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

            // Assert
            Assert.NotNull(modelBindingResult);
            Assert.True(modelBindingResult.IsModelSet);

            var model = Assert.IsType<List<IFormCollection>>(modelBindingResult.Model);
            Assert.Equal(1, model.Count);
            Assert.NotNull(model[0]);

            Assert.Equal(0, modelState.Count);
            Assert.Equal(0, modelState.ErrorCount);
            Assert.True(modelState.IsValid);
        }
开发者ID:njannink,项目名称:sonarlint-vs,代码行数:32,代码来源:GenericModelBinderIntegrationTest.cs


示例20: JsonPatchInputFormatter_ReadsMultipleOperations_Successfully

        public async Task JsonPatchInputFormatter_ReadsMultipleOperations_Successfully()
        {
            // Arrange
            var logger = GetLogger();
            var formatter = new JsonPatchInputFormatter(logger);
            var content = "[{\"op\": \"add\", \"path\" : \"Customer/Name\", \"value\":\"John\"}," +
                "{\"op\": \"remove\", \"path\" : \"Customer/Name\"}]";
            var contentBytes = Encoding.UTF8.GetBytes(content);

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

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

            // Assert
            Assert.False(result.HasError);
            var patchDoc = Assert.IsType<JsonPatchDocument<Customer>>(result.Model);
            Assert.Equal("add", patchDoc.Operations[0].op);
            Assert.Equal("Customer/Name", patchDoc.Operations[0].path);
            Assert.Equal("John", patchDoc.Operations[0].value);
            Assert.Equal("remove", patchDoc.Operations[1].op);
            Assert.Equal("Customer/Name", patchDoc.Operations[1].path);
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:32,代码来源:JsonPatchInputFormatterTest.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ModelType类代码示例发布时间:2022-05-24
下一篇:
C# ModelState类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap