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


C# ModelStateDictionary.AddModelError方法代码示例

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


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

示例1: IsValidBooleanField

 public static bool IsValidBooleanField(ModelStateDictionary modelState, string display, string field, string value, bool required = false)
 {
     bool ret = false;
     bool result;
     if (value.IsNullOrEmpty())
     {
         if (required)
         {
             modelState.AddModelError(field, "กรุณาใส่" + display);
         }
         else
         {
             ret = true;
         }
     }
     else if (!bool.TryParse(value, out result))
     {
         modelState.AddModelError(field, display + "มีค่าไม่ถูกต้อง");
     }
     else
     {
         ret = true;
     }
     return ret;
 }
开发者ID:phithakul,项目名称:JBus,代码行数:25,代码来源:ValidationHelper.cs

示例2: OnActionExecuting

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);

            var options = actionContext.ActionArguments.Where(p => p.Value is ODataQueryOptions).Select(p => p.Value).OfType<ODataQueryOptions>().FirstOrDefault();

            if (options == null)
            {
                return;
            }

            var modelDictionary = new ModelStateDictionary();

            if (options.Skip != null)
            {
                if (options.Skip.Value < MinSkipValue)
                {
                    modelDictionary.AddModelError("Skip", String.Format("Value must be greater than or equal {0}", MinSkipValue));
                }
            }

            if (options.Top != null)
            {
                if (options.Top.Value < MinTopValue)
                {
                    modelDictionary.AddModelError("Top", String.Format("Value must be greater than or equal {0}", MinTopValue));
                }
            }

            if (modelDictionary.Count > 0)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelDictionary);
            }
        }
开发者ID:GusLab,项目名称:video-portal,代码行数:34,代码来源:ODataValidationAttribute.cs

示例3: WriteXml_WritesValidXml

        public void WriteXml_WritesValidXml()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.AddModelError("key1", "Test Error 1");
            modelState.AddModelError("key1", "Test Error 2");
            modelState.AddModelError("key2", "Test Error 3");
            var serializableError = new SerializableError(modelState);
            var outputStream = new MemoryStream();

            // Act
            using (var xmlWriter = XmlWriter.Create(outputStream))
            {
                var dataContractSerializer = new DataContractSerializer(typeof(SerializableErrorWrapper));
                dataContractSerializer.WriteObject(xmlWriter, new SerializableErrorWrapper(serializableError));
            }
            outputStream.Position = 0;
            var res = new StreamReader(outputStream, Encoding.UTF8).ReadToEnd();

            // Assert
            var expectedContent =
                TestPlatformHelper.IsMono ?
                    "<?xml version=\"1.0\" encoding=\"utf-8\"?><Error xmlns:i=\"" +
                    "http://www.w3.org/2001/XMLSchema-instance\"><key1>Test Error 1 Test Error 2</key1>" +
                    "<key2>Test Error 3</key2></Error>" :
                    "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                    "<Error><key1>Test Error 1 Test Error 2</key1><key2>Test Error 3</key2></Error>";

            Assert.Equal(expectedContent, res);
        }
开发者ID:notami18,项目名称:Mvc,代码行数:30,代码来源:SerializableErrorWrapperTests.cs

示例4: Validate

        public void Validate(ModelStateDictionary modelState, string modelPrefix, decimal? totalMarks)
        {
            if (!this.IsSet)
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(this.Grade))
            {
                modelState.AddModelError(modelPrefix + ".Grade", "Grade is required.");
            }

            if (!this.MinResult.HasValue)
            {
                modelState.AddModelError(modelPrefix + ".MinResult", "Minium required result is required.");
            }
            else
            {
                if (this.MinResult < 0)
                {
                    modelState.AddModelError(modelPrefix + ".MinResult", "Min result cannot be negative.");
                }

                if (totalMarks.HasValue && this.MinResult > totalMarks)
                {
                    modelState.AddModelError(modelPrefix + ".MinResult", "Min result must be less than total marks.");
                }
            }
        }
开发者ID:pebblecode,项目名称:AssessmentAnywhere,代码行数:29,代码来源:UpdatedGradeBoundary.cs

示例5: AddModelError_WithErrorString_AddsTooManyModelErrors_WhenMaxErrorsIsReached

        public void AddModelError_WithErrorString_AddsTooManyModelErrors_WhenMaxErrorsIsReached()
        {
            // Arrange
            var expected = "The maximum number of allowed model errors has been reached.";
            var dictionary = new ModelStateDictionary
            {
                MaxAllowedErrors = 5
            };
            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), nameof(string.Length));
            dictionary.AddModelError("key1", "error1");
            dictionary.AddModelError("key2", new Exception(), metadata);
            dictionary.AddModelError("key3", new Exception(), metadata);
            dictionary.AddModelError("key4", "error4");
            dictionary.AddModelError("key5", "error5");

            // Act and Assert
            Assert.True(dictionary.HasReachedMaxErrors);
            Assert.Equal(5, dictionary.ErrorCount);
            var error = Assert.Single(dictionary[string.Empty].Errors);
            Assert.IsType<TooManyModelErrorsException>(error.Exception);
            Assert.Equal(expected, error.Exception.Message);

            // TooManyModelErrorsException added instead of key5 error.
            Assert.DoesNotContain("key5", dictionary.Keys);
        }
开发者ID:ymd1223,项目名称:Mvc,代码行数:26,代码来源:ModelStateDictionaryTest.cs

示例6: Validate

        public void Validate(ModelStateDictionary modelState, string prefix, decimal? totalMarks)
        {
            if (string.IsNullOrWhiteSpace(this.Surname))
            {
                modelState.AddModelError(prefix + ".Surname", "Surname cannot be blank.");
            }

            if (string.IsNullOrWhiteSpace(this.Forenames))
            {
                modelState.AddModelError(prefix + ".Forenames", "Forenames cannot be blank.");
            }

            if (!this.Result.HasValue)
            {
                return;
            }

            if (this.Result < 0)
            {
                modelState.AddModelError(prefix + ".Result", "Result must be a positive number.");
            }

            if (totalMarks.HasValue && this.Result > totalMarks)
            {
                modelState.AddModelError(prefix + ".Result", "Result cannot be greater than the total marks.");
            }
        }
开发者ID:pebblecode,项目名称:AssessmentAnywhere,代码行数:27,代码来源:UpdateResultRow.cs

示例7: StartRegistrationForFamilyMember

        public void StartRegistrationForFamilyMember(int id, ModelStateDictionary modelState)
        {
            modelState.Clear(); // ensure we pull form fields from our model, not MVC's
            HistoryAdd("Register");
            int index = List.Count - 1;
            var p = LoadExistingPerson(id, index);

            if(p.NeedsToChooseClass())
                return;

            p.ValidateModelForFind(modelState, id, selectFromFamily: true);
            if (!modelState.IsValid)
                return;

            List[index] = p;

            if (p.ManageSubscriptions() && p.Found == true)
                return;

            if (p.org != null && p.Found == true)
            {
                if (!SupportMissionTrip)
                    p.IsFilled = p.org.RegLimitCount(DbUtil.Db) >= p.org.Limit;
                if (p.IsFilled)
                    modelState.AddModelError(this.GetNameFor(mm => mm.List[List.IndexOf(p)].Found),
                        "Sorry, but registration is filled.");
                if (p.Found == true)
                    p.FillPriorInfo();
                return;
            }
            if (p.org == null && p.ComputesOrganizationByAge())
                modelState.AddModelError(this.GetNameFor(mm => mm.List[id].Found), p.NoAppropriateOrgError);
        }
开发者ID:craigsaboe,项目名称:bvcms,代码行数:33,代码来源:FamilyMembers.cs

示例8: ValidateCreditCardInfo

        public static void ValidateCreditCardInfo(ModelStateDictionary modelState, PaymentForm pf)
        {
            if (pf.SavePayInfo && pf.CreditCard.HasValue() && pf.CreditCard.StartsWith("X"))
                return;

            if (!ValidateCard(pf.CreditCard, pf.SavePayInfo))
            {
                modelState.AddModelError("CreditCard", "The card number is invalid.");
            }
            if (!pf.Expires.HasValue())
            {
                modelState.AddModelError("Expires", "The expiration date is required.");
                return;
            }

            var exp = DbUtil.NormalizeExpires(pf.Expires);
            if (exp == null)
                modelState.AddModelError("Expires", "The expiration date format is invalid (MMYY).");

            if (!pf.CVV.HasValue())
            {
                modelState.AddModelError("CVV", "The CVV is required.");
                return;
            }

            var cvvlen = pf.CVV.GetDigits().Length;
            if (cvvlen < 3 || cvvlen > 4)
                modelState.AddModelError("CVV", "The CVV must be a 3 or 4 digit number.");
        }
开发者ID:stevesloka,项目名称:bvcms,代码行数:29,代码来源:PaymentValidator.cs

示例9: WithModelStateForShouldThrowExceptionWhenModelStateHasSameErrors

        public void WithModelStateForShouldThrowExceptionWhenModelStateHasSameErrors()
        {
            Test.AssertException<ModelErrorAssertionException>(
                () =>
                {
                    var requestModelWithErrors = TestObjectFactory.GetRequestModelWithErrors();
                    var modelState = new ModelStateDictionary();
                    modelState.AddModelError("Integer", "The field Integer must be between 1 and 2147483647.");
                    modelState.AddModelError("RequiredString", "The RequiredString field is required.");

                    MyController<MvcController>
                        .Instance()
                        .Calling(c => c.BadRequestWithModelState(requestModelWithErrors))
                        .ShouldReturn()
                        .BadRequest()
                        .WithModelStateError(modelStateError => modelStateError
                            .For<RequestModel>()
                            .ContainingErrorFor(m => m.Integer).ThatEquals("The field Integer 1 must be between 1 and 2147483647.")
                            .AndAlso()
                            .ContainingErrorFor(m => m.RequiredString).BeginningWith("The RequiredString")
                            .AndAlso()
                            .ContainingErrorFor(m => m.RequiredString).EndingWith("required.")
                            .AndAlso()
                            .ContainingErrorFor(m => m.RequiredString).Containing("field")
                            .AndAlso()
                            .ContainingNoErrorFor(m => m.NonRequiredString));
                },
                "When calling BadRequestWithModelState action in MvcController expected error message for key Integer to be 'The field Integer 1 must be between 1 and 2147483647.', but instead found 'The field Integer must be between 1 and 2147483647.'.");
        }
开发者ID:ivaylokenov,项目名称:MyTested.AspNetCore.Mvc,代码行数:29,代码来源:BadRequestTestBuilderTests.cs

示例10: Validate

		public void Validate(ModelStateDictionary modelStateDictionary, IUserService userService, string ip)
		{
			if (!IsCoppa)
				modelStateDictionary.AddModelError("IsCoppa", Resources.MustBe13);
			if (!IsTos)
				modelStateDictionary.AddModelError("IsTos", Resources.MustAcceptTOS);
			userService.IsPasswordValid(Password, modelStateDictionary);
			if (Password != PasswordRetype)
				modelStateDictionary.AddModelError("PasswordRetype", Resources.RetypeYourPassword);
			if (String.IsNullOrWhiteSpace(Name))
				modelStateDictionary.AddModelError("Name", Resources.NameRequired);
			else if (userService.IsNameInUse(Name))
				modelStateDictionary.AddModelError("Name", Resources.NameInUse);
			if (String.IsNullOrWhiteSpace(Email))
				modelStateDictionary.AddModelError("Email", Resources.EmailRequired);
			else
				if (!Email.IsEmailAddress())
					modelStateDictionary.AddModelError("Email", Resources.ValidEmailAddressRequired);
				else if (Email != null && userService.IsEmailInUse(Email))
					modelStateDictionary.AddModelError("Email", Resources.EmailInUse);
			if (Email != null && userService.IsEmailBanned(Email))
				modelStateDictionary.AddModelError("Email", Resources.EmailBanned);
			if (userService.IsIPBanned(ip))
				modelStateDictionary.AddModelError("Email", Resources.IPBanned);
		}
开发者ID:andyliyuze,项目名称:POPForums,代码行数:25,代码来源:SignupData.cs

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

示例12: SignUp

        public SignUpViewModel SignUp(SignUpActionData actionData)
        {
            var viewModel = new SignUpViewModel();

            var modelStates = new ModelStateDictionary();

            foreach (var reason in actionData.RegistrationFailureReasons) {
                switch (reason) {
                    case RegistrationFailureReason.UsernameNotAvailable:
                        modelStates.AddModelError("username", GetRegistrationFailureReasonText(RegistrationFailureReason.UsernameNotAvailable));
                        break;
                    case RegistrationFailureReason.PasswordsDoNotMatch:
                        modelStates.AddModelError("passwordConfirmation", GetRegistrationFailureReasonText(RegistrationFailureReason.PasswordsDoNotMatch));
                        break;
                    case RegistrationFailureReason.EmailsDoNotMatch:
                        modelStates.AddModelError("email", GetRegistrationFailureReasonText(RegistrationFailureReason.EmailsDoNotMatch));
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }

            IEnumerable<string> errors = actionData.RegistrationFailureReasons.Select(GetRegistrationFailureReasonText);
            viewModel.Errors = errors;
            viewModel.ModelState = modelStates;
            return viewModel;
        }
开发者ID:rgavrilov,项目名称:thcard,代码行数:27,代码来源:AccountPresenter.cs

示例13: IsValidEmailField

 public static bool IsValidEmailField(ModelStateDictionary modelState, string display, string field, string value, int maxLength, bool required = false)
 {
     bool ret = false;
     if (value.IsNullOrEmpty())
     {
         if (required)
         {
             modelState.AddModelError(field, "กรุณาใส่" + display);
         }
         else
         {
             ret = true;
         }
     }
     else if (value.Length > maxLength)
     {
         modelState.AddModelError(field, string.Format("{0}ต้องมีความยาวไม่เกิน {1} ตัวอักษร", display, maxLength));
     }
     else if (!new EmailAddressAttribute().IsValid(value))
     {
         modelState.AddModelError(field, string.Format("{0}มีรูปแบบไม่ถูกต้อง", display));
     }
     else
     {
         ret = true;
     }
     return ret;
 }
开发者ID:phithakul,项目名称:JBus,代码行数:28,代码来源:ValidationHelper.cs

示例14: ValidateBankAccountInfo

 public static void ValidateBankAccountInfo(ModelStateDictionary ModelState, string Routing, string Account)
 {
     if (!checkABA(Routing))
         ModelState.AddModelError("Routing", "invalid routing number");
     if (!Account.HasValue())
         ModelState.AddModelError("Account", "need account number");
     else if (!Account.StartsWith("X") && Account.Length <= 4)
         ModelState.AddModelError("Account", "please enter entire account number with any leading zeros");
 }
开发者ID:rossspoon,项目名称:bvcms,代码行数:9,代码来源:Payments.cs

示例15: HandleErrorDict

        public static void HandleErrorDict(ModelStateDictionary stateDictionary, Dictionary<string, string> validationsDictionary)
        {
            if (validationsDictionary.Any()) {
                stateDictionary.AddModelError(String.Empty, "Please review and correct the noted errors.");
            }

            foreach (KeyValuePair<string, string> valuePair in validationsDictionary) {
                stateDictionary.AddModelError(valuePair.Key, valuePair.Value);
            }
        }
开发者ID:sunsiz,项目名称:CarrotCakeCMS-MVC,代码行数:10,代码来源:Helper.cs


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