Example #1
0
 private void ConstructErrorMessages(ActionContext context)
 {
     foreach (var keyModelStatePair in context.ModelState)
     {
         string key = keyModelStatePair.Key;
         ModelErrorCollection errors = keyModelStatePair.Value.Errors;
         if (errors != null && errors.Count > 0)
         {
             if (errors.Count == 1)
             {
                 var errorMessage = GetErrorMessage(errors[0]);
                 Errors.Add(key, new[] { errorMessage });
             }
             else
             {
                 var errorMessages = new string[errors.Count];
                 for (var i = 0; i < errors.Count; i++)
                 {
                     errorMessages[i] = GetErrorMessage(errors[i]);
                 }
                 Errors.Add(key, errorMessages);
             }
         }
     }
 }
Example #2
0
        /// <summary>
        /// Generates the error message details.
        /// </summary>
        /// <param name="modelState">State of the model.</param>
        /// <returns></returns>
        private string GenerateErrorMessageDetails(ModelStateDictionary modelState)
        {
            var errorMessages = new List <string>();

            foreach (KeyValuePair <string, ModelState> keyModelStatePair in modelState)
            {
                ModelErrorCollection errors = keyModelStatePair.Value.Errors;

                if (errors != null && errors.Count > 0)
                {
                    errorMessages.AddRange(
                        errors
                        .Select(error =>
                    {
                        if (!string.IsNullOrEmpty(error.ErrorMessage))
                        {
                            return(error.ErrorMessage);
                        }

                        if (error.Exception != null && !string.IsNullOrEmpty(error.Exception.Message))
                        {
                            return(error.Exception.Message);
                        }

                        return(string.Empty);
                    })
                        .ToArray()
                        );
                }
            }

            return(string.Join(" <> ", errorMessages));
        }
Example #3
0
        public static string CustomValidationMessage(this HtmlHelper instance, string modelName)
        {
            Check.Argument.IsNotNull(instance, "instance");
            Check.Argument.IsNotNull(modelName, "modelName");

            TagBuilder builder = new TagBuilder("span");

            builder.MergeAttribute("class", HtmlHelper.ValidationMessageCssClassName);

            if (instance.ViewData.ModelState.ContainsKey(modelName))
            {
                ModelState           modelState  = instance.ViewData.ModelState[modelName];
                ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors;
                ModelError           modelError  = ((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors[0];

                if (modelError != null)
                {
                    string validationMessage = GetValidationMessage(modelError);

                    TagBuilder iconBuilder = new TagBuilder("img");

                    iconBuilder.MergeAttribute("src", instance.ViewContext.RequestContext.UrlHelper().InputValidationErrorIcon());
                    iconBuilder.MergeAttribute("alt", string.Empty);
                    iconBuilder.MergeAttribute("title", validationMessage);

                    builder.InnerHtml = iconBuilder.ToString(TagRenderMode.SelfClosing);
                }
            }

            return(builder.ToString());
        }
Example #4
0
        // ValidationLabel
        public static MvcHtmlString ValidationLabel(this HtmlHelper htmlHelper,
                                                    string modelName,
                                                    string labelText,
                                                    IDictionary <string, object> htmlAttributes)
        {
            if (modelName == null)
            {
                throw new ArgumentNullException("modelName");
            }
            ModelState           modelState  = htmlHelper.ViewData.ModelState[modelName];
            ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors;
            ModelError           modelError  = ((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors[0];
            // If there is no error, we want to show a label.  If there is an error,
            // we want to show the error message.
            string tagText  = labelText;
            string tagClass = "form_field_label_normal";

            if ((modelState != null) && (modelError != null))
            {
                tagText  = modelError.ErrorMessage;
                tagClass = "form_field_label_error";
            }
            // Build out the tag
            TagBuilder builder = new TagBuilder("label");

            builder.MergeAttributes(htmlAttributes);
            builder.MergeAttribute("class", tagClass);
            builder.MergeAttribute("validationlabelfor", modelName);
            builder.SetInnerText(tagText);
            return(MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal)));
        }
Example #5
0
        private static bool HasError(this HtmlHelper htmlHelper, ModelMetadata modelMetadata, string expression)
        {
            string      modelName   = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
            FormContext formContext = htmlHelper.ViewContext.FormContext;

            if (formContext == null)
            {
                return(false);
            }

            if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName))
            {
                return(false);
            }

            ModelState modelState = htmlHelper.ViewData.ModelState[modelName];

            if (modelState == null)
            {
                return(false);
            }

            ModelErrorCollection modelErrors = modelState.Errors;

            if (modelErrors == null)
            {
                return(false);
            }

            return(modelErrors.Count > 0);
        }
Example #6
0
        void _Initialise(ViewContext viewContext)
        {
            if (viewContext == null)
            {
                throw new ArgumentNullException("viewContext");
            }

            ViewDataDictionary viewData = viewContext.ViewData;

            if (!viewData.ModelState.ContainsKey(ModelName))
            {
                return;
            }

            ModelErrorCollection modelErrors = viewData.ModelState.GetErrors(ModelName);

            if (modelErrors == null || modelErrors.Count == 0)
            {
                return;
            }

            string errorMessage = string.IsNullOrEmpty(ErrorMessage) ? modelErrors[0].ErrorMessage : ErrorMessage;

            SetInnerText(errorMessage);
            Title = errorMessage;
        }
Example #7
0
        public static string ValidationMessage(this HtmlHelper htmlHelper, string modelName, string validationMessage, IDictionary <string, object> htmlAttributes)
        {
            if (modelName == null)
            {
                throw new ArgumentNullException("modelName");
            }

            if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName))
            {
                return(null);
            }

            ModelState           modelState  = htmlHelper.ViewData.ModelState[modelName];
            ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors;
            ModelError           modelError  = ((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors[0];

            if (modelError == null)
            {
                return(null);
            }

            TagBuilder builder = new TagBuilder("span");

            builder.MergeAttributes(htmlAttributes);
            builder.MergeAttribute("class", HtmlHelper.ValidationMessageCssClassName);
            builder.SetInnerText(String.IsNullOrEmpty(validationMessage) ? GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, modelState) : validationMessage);

            return(builder.ToString(TagRenderMode.Normal));
        }
    public ApiProblemDetails(
        ModelStateDictionary modelState,
        HttpStatusCode statusCode,
        string?message = null,
        IReadOnlyDictionary <string, string[]>?additionalInfo = null
        )
    {
        Message        = message;
        StatusCode     = (int)statusCode;
        AdditionalInfo = additionalInfo;

        Dictionary <string, string[]> errors = new Dictionary <string, string[]>(StringComparer.Ordinal);

        foreach (KeyValuePair <string, ModelStateEntry> keyModelStatePair in modelState)
        {
            string key = keyModelStatePair.Key;
            ModelErrorCollection errorCollection = keyModelStatePair.Value.Errors;
            if (errorCollection != null && errorCollection.Count != 0)
            {
                List <string> errorStrings = errorCollection.Select(GetErrorMessage).ToList();
                if (keyModelStatePair.Value.AttemptedValue != null)
                {
                    errorStrings.Add(keyModelStatePair.Value.AttemptedValue);
                }

                errors.Add(key, errorStrings.ToArray());
            }
        }

        Errors = errors;
        public static MvcHtmlString ValidationMessageCustom(this HtmlHelper htmlHelper, string modelName)
        {
            //<span class="text-danger field-validation-error" data-valmsg-for="@field.Name" data-valmsg-replace="true">
            //@if(!ViewData.ModelState.IsValid && ViewData.ModelState[field.Name] != null && ViewData.ModelState[field.Name].Errors.Count > 0)
            //{
            //    <span for= "@field.Name" class="">@ViewData.ModelState[field.Name].Errors.First().ErrorMessage</span>
            //}
            //</span>

            TagBuilder builder = new TagBuilder("span");

            builder.AddCssClass("text-danger");
            builder.AddCssClass("field-validation-error");

            builder.Attributes.Add("data-valmsg-for", modelName);
            builder.Attributes.Add("data-valmsg-replace", "true");

            ModelState           modelState  = htmlHelper.ViewData.ModelState[modelName];
            ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors;
            ModelError           modelError  = (((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors.FirstOrDefault(m => !String.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0]);

            if (htmlHelper.ViewData.ModelState.IsValid && modelError != null)
            {
                TagBuilder errorMessageSpan = new TagBuilder("span");
                errorMessageSpan.Attributes.Add("for", modelName);
                errorMessageSpan.SetInnerText(modelError.ErrorMessage);
                builder.InnerHtml = errorMessageSpan.ToString();
            }

            return(MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal)));
        }
Example #10
0
 public ModeValidationContext(HttpContext httpContext, ModelStateDictionary modelState, string firstField, ModelErrorCollection errors)
 {
     HttpContext = httpContext;
     ModelState  = modelState;
     FirstField  = firstField;
     Errors      = errors;
 }
Example #11
0
        public static IHtmlString ValidationMessageForInput(this HtmlHelper htmlHelper, string inputName, IDictionary <string, object> htmlAttributes)
        {
            var    validationMessage = "";
            string fullHtmlFieldName = inputName;

            if (!htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled)
            {
                throw new KoobooException("Kooboo.Web.Mvc.Html.ValidationExtensions.ValidationMessageForInput only support UnobtrusiveJavaScriptEnabled.");
            }
            ModelState           modelState = htmlHelper.ViewData.ModelState[fullHtmlFieldName];
            ModelErrorCollection errors     = (modelState == null) ? null : modelState.Errors;
            ModelError           error      = ((errors == null) || (errors.Count == 0)) ? null : errors[0];

            TagBuilder builder = new TagBuilder("span");

            builder.MergeAttributes <string, object>(htmlAttributes);
            builder.AddCssClass((error != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName);
            if (!string.IsNullOrEmpty(validationMessage))
            {
                builder.SetInnerText(validationMessage);
            }
            else if (error != null)
            {
                builder.SetInnerText(GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, error, modelState));
            }

            bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage);

            builder.MergeAttribute("data-valmsg-for", fullHtmlFieldName);
            builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant());

            return(new HtmlString(builder.ToString(TagRenderMode.Normal)));
        }
Example #12
0
        /// <summary>
        ///     根据指定的属性名或模型对象的名称,从模型错误中显示一个错误信息对应的HTML标记。
        /// </summary>
        /// <param name="helper">HTML帮助器实例。</param>
        /// <param name="modelName">所验证的属性或模型对象的名称。</param>
        /// <param name="htmlAttributes">包含元素 HTML 特性的对象。</param>
        /// <returns></returns>
        public static MvcHtmlString PropertyValidationMessage(this HtmlHelper helper, string modelName,
                                                              object htmlAttributes)
        {
            modelName = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(modelName);
            if (!helper.ViewData.ModelState.ContainsKey(modelName))
            {
                return(null);
            }

            ModelState           modelState  = helper.ViewData.ModelState[modelName];
            ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors;
            ModelError           modelError  = (((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors.FirstOrDefault(m => !String.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0]);

            if (modelError == null)
            {
                return(null);
            }

            TagBuilder builder = new TagBuilder("label");

            builder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
            builder.AddCssClass("error");
            builder.MergeAttribute("id", $"{modelName}-error");
            builder.MergeAttribute("for", modelName);

            var iTag = new TagBuilder("i");

            iTag.AddCssClass("fa fa-times-circle");

            builder.InnerHtml = iTag.ToString(TagRenderMode.Normal) + GetUserErrorMessageOrDefault(helper.ViewContext.HttpContext, modelError, modelState);
            return(new MvcHtmlString(builder.ToString(TagRenderMode.Normal)));
        }
 public static FormFactoryModelStateErrors ToFfModelStateErrors(this ModelErrorCollection mvcErrors)
 {
     return(new FormFactoryModelStateErrors(mvcErrors.Select(e => new FormFactoryModelStateError()
     {
         ErrorMessage = e.ErrorMessage
     })));
 }
        public ModelStateValidationProblemDetails(ModelStateDictionary modelState)
            : this()
        {
            if (modelState == null)
            {
                throw new ArgumentNullException(nameof(modelState));
            }

            foreach (KeyValuePair <string, ModelStateEntry> keyValuePair in modelState)
            {
                string key = keyValuePair.Key;
                ModelErrorCollection errors = keyValuePair.Value.Errors;

                if (errors != null && errors.Any())
                {
                    var errorMessages = new List <string>();

                    for (var index = 0; index < errors.Count; ++index)
                    {
                        errorMessages.Add(GetErrorMessage(errors[index]));
                    }

                    Errors.Add(new ValidationProblem(key, errorMessages));
                }
            }
        }
Example #15
0
        /// <summary>
        /// 将modelState的第一条转为ResultMessage
        /// </summary>
        /// <param name="modelState"></param>
        /// <returns></returns>
        public static ResultMessage ToResultMessageFirst(this ModelStateDictionary modelState)
        {
            var list = modelState.ToList();

            if (list.Count() == 0)
            {
                return(new ResultMessage()
                {
                    Status = "0", Message = "Can not find ModelStateDictionary"
                });
            }
            ModelErrorCollection modelErrors = list[0].Value.Errors;

            if (modelErrors.Count() == 0)
            {
                return(new ResultMessage()
                {
                    Status = "0", Message = "Can not find ModelErrorCollection"
                });
            }
            return(new ResultMessage()
            {
                Status = "0", Message = modelErrors[0].ErrorMessage
            });
        }
        public void OnActionExecuting_Should_Update_Result_When_Model_Is_Invalid()
        {
            var actionContext = new ActionContext
            {
                HttpContext      = new DefaultHttpContext(),
                RouteData        = new RouteData(),
                ActionDescriptor = new ActionDescriptor()
            };
            var context = new ActionExecutingContext(actionContext, Substitute.For <IList <IFilterMetadata> >(), Substitute.For <IDictionary <string, object> >(), null);

            var field   = "field";
            var message = "validation message";

            actionContext.ModelState.AddModelError(field, message);
            var errors = new ModelErrorCollection();

            errors.Add(message);
            var data = new [] { new { Key = field, Errors = errors } };

            _filter.OnActionExecuting(context);

            context.Result.Should().BeAssignableTo <ObjectResult>();
            context.Result.As <ObjectResult>().StatusCode.Should().Be(StatusCodes.Status400BadRequest);
            context.Result.As <ObjectResult>().Value.Should().BeAssignableTo <ApiResponse>();
            context.Result.As <ObjectResult>().Value.As <ApiResponse>().Success.Should().BeFalse();
            context.Result.As <ObjectResult>().Value.As <ApiResponse>().Message.Should().Be("Invalid request format.");
            context.Result.As <ObjectResult>().Value.As <ApiResponse>().Data.Should().BeEquivalentTo(data);
        }
Example #17
0
        public static ModelErrorCollection Validar(Usuario usuario, Boolean validarSenha = true)
        {
            var mensagens = new ModelErrorCollection();

            if (String.IsNullOrWhiteSpace(usuario.Email))
            {
                mensagens.Add("É obrigatório fornecer o e-mail do usuário");
            }

            if (validarSenha && String.IsNullOrWhiteSpace(usuario.Senha))
            {
                mensagens.Add("É obrigatório fornecer a senha do usuário");
            }


            if (validarSenha && !String.IsNullOrWhiteSpace(usuario.Senha) && usuario.Senha.Length < 6)
            {
                mensagens.Add("A senha deve ter no mínimo 6 caracteres");
            }

            if (String.IsNullOrWhiteSpace(usuario.Nome))
            {
                mensagens.Add("É obrigatório fornecer o nome do usuário");
            }

            if (usuario.Perfis == null || usuario.Perfis.Count() == 0)
            {
                mensagens.Add("É obrigatório relacionar ao menos um perfil ao usuário");
            }

            return(mensagens);
        }
Example #18
0
        /// <summary>
        /// 输入拦截器
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.ModelState.IsValid)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var m in actionContext.ModelState)
                {
                    string[] key = m.Key.Split(".".ToCharArray());
                    string   err = key.Length == 2 ? key[1] + "^" : "";

                    ModelErrorCollection errors = m.Value.Errors;
                    foreach (ModelError error in errors)
                    {
                        err += error.ErrorMessage + ",";
                    }
                    err = err.Substring(0, err.Length - 1) + "|";
                    sb.Append(err);
                }

                var resultMsg = new BaseJsonResult <string>
                {
                    Status  = (int)JsonObjectStatus.ParameterError,
                    Message = sb.ToString().Substring(0, sb.ToString().Length - 1),
                };

                actionContext.Response = resultMsg.TryToHttpResponseMessage();
            }
            base.OnActionExecuting(actionContext);
        }
Example #19
0
        public static ModelErrorCollection AsModelErrorCollection(this string message)
        {
            var collection = new ModelErrorCollection();

            collection.Add(message);

            return(collection);
        }
 private void DoSetup()
 {
     if (modelState != null)
     {
         Errors = modelState.Errors;
     }
     
 }
Example #21
0
        public static ModelErrorCollection AsModelErrorCollection(this Exception ex)
        {
            var collection = new ModelErrorCollection();

            collection.Add(ex);

            return(collection);
        }
 protected ModelErrorCollection GetModelErrors()
 {
     ModelErrorCollection modelError = new ModelErrorCollection();
     foreach (ModelError error in ViewData.ModelState.Values.SelectMany(entry => entry.Errors))
     {
         modelError.Add(error);
     }
     return modelError;
 }
Example #23
0
        private static MvcHtmlString ValidationMessageHelper(this HtmlHelper htmlHelper, ModelMetadata modelMetadata, string expression, string validationMessage, IDictionary <string, object> htmlAttributes)
        {
            string      modelName   = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
            FormContext formContext = htmlHelper.ViewContext.GetFormContextForClientValidation();

            if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName) && formContext == null)
            {
                return(null);
            }

            ModelState           modelState  = htmlHelper.ViewData.ModelState[modelName];
            ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors;
            ModelError           modelError  = (((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors.FirstOrDefault(m => !String.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0]);

            if (modelError == null && formContext == null)
            {
                return(null);
            }

            TagBuilder builder = new TagBuilder("span");

            builder.MergeAttributes(htmlAttributes);
            builder.AddCssClass((modelError != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName);

            if (!String.IsNullOrEmpty(validationMessage))
            {
                builder.SetInnerText(validationMessage);
            }
            else if (modelError != null)
            {
                builder.SetInnerText(GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, modelState));
            }

            if (formContext != null)
            {
                bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage);

                if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled)
                {
                    builder.MergeAttribute("data-valmsg-for", modelName);
                    builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant());
                }
                else
                {
                    FieldValidationMetadata fieldMetadata = ApplyFieldValidationMetadata(htmlHelper, modelMetadata, modelName);
                    // rules will already have been written to the metadata object
                    fieldMetadata.ReplaceValidationMessageContents = replaceValidationMessageContents; // only replace contents if no explicit message was specified

                    // client validation always requires an ID
                    builder.GenerateId(modelName + "_validationMessage");
                    fieldMetadata.ValidationMessageId = builder.Attributes["id"];
                }
            }

            return(builder.ToMvcHtmlString(TagRenderMode.Normal));
        }
Example #24
0
        private List <string> CollectMessages(ModelErrorCollection modelErrorCollection)
        {
            List <string> errors = new List <string>();

            modelErrorCollection.ToList().ForEach(
                error => errors.Add(error.ErrorMessage)
                );

            return(errors);
        }
Example #25
0
        public Field(string name, ModelErrorCollection messages)
        {
            Name     = name;
            Messages = new List <string>();

            foreach (var error in messages)
            {
                Messages.Add(error.ErrorMessage);
            }
        }
 private static IEnumerable <FormFactoryModelStateError> Transform(ModelErrorCollection errors)
 {
     foreach (var error in errors)
     {
         yield return(new FormFactoryModelStateError()
         {
             ErrorMessage = error.ErrorMessage
         });
     }
 }
        protected ModelErrorCollection GetModelErrors()
        {
            ModelErrorCollection modelError = new ModelErrorCollection();

            foreach (ModelError error in ViewData.ModelState.Values.SelectMany(entry => entry.Errors))
            {
                modelError.Add(error);
            }
            return(modelError);
        }
 private static IEnumerable<FormFactoryModelStateError> Transform(ModelErrorCollection errors)
 {
     foreach (var error in errors)
     {
         yield return new FormFactoryModelStateError()
         {
             ErrorMessage = error.ErrorMessage
         };
     }
 }
 protected string Errors(ModelErrorCollection modelError)
 {
     if (modelError == null) return (string.Empty);
     StringBuilder sb = new StringBuilder();
     sb.Append(Environment.NewLine);
     foreach (var tag  in modelError)
     {
         sb.Append(tag.ErrorMessage+",");
     }
     return (sb.ToString().TrimEnd((',')));
 }
 static bool IsErrorAvalilableIn(ModelErrorCollection errors, string errorMessage)
 {
     foreach (var error in errors)
     {
         if (error.ErrorMessage == errorMessage)
         {
             return(true);
         }
     }
     return(false);
 }
Example #31
0
        public static ModelErrorCollection AsModelErrorCollection(this ModelStateDictionary modelState)
        {
            var collection = new ModelErrorCollection();

            modelState.Values.SelectMany(v => v.Errors)
            .Select(e => e.ErrorMessage)
            .ToList()
            .ForEach(message => collection.Add(message));

            return(collection);
        }
Example #32
0
        private static List <ExceptionModel> Create(ModelErrorCollection errors, string key)
        {
            List <ExceptionModel> exceptions = new List <ExceptionModel>();

            foreach (var error in errors)
            {
                exceptions.Add(Create(error, key));
            }

            return(exceptions);
        }
Example #33
0
        private string ModelErrorsToOrderedList(ModelErrorCollection errors)
        {
            var stbList = new StringBuilder();

            foreach (ModelError error in errors)
            {
                stbList.AppendFormat("<li>{0}</li>", error.ErrorMessage);
            }

            return(stbList.ToString());
        }
Example #34
0
        public static List <ErrorElement> InitPropertyErrorElements(ModelErrorCollection errors)
        {
            if (errors is null)
            {
                return(null);
            }

            var tempOfErrorElements = new List <ErrorElement>();

            foreach (var error in errors)
            {
                tempOfErrorElements.Add(item: new ErrorElement(element: Span.Render(cssId: default, cssClass: default, spanContent: error.ErrorMessage), error));
        public void AddWithExceptionArgument()
        {
            // Arrange
            ModelErrorCollection collection = new ModelErrorCollection();
            Exception ex = new Exception("some message");

            // Act
            collection.Add(ex);

            // Assert
            ModelError modelError = Assert.Single(collection);
            Assert.Same(ex, modelError.Exception);
        }
        public void AddWithStringArgument()
        {
            // Arrange
            ModelErrorCollection collection = new ModelErrorCollection();

            // Act
            collection.Add("some message");

            // Assert
            ModelError modelError = Assert.Single(collection);
            Assert.Equal("some message", modelError.ErrorMessage);
            Assert.Null(modelError.Exception);
        }
        public void AddWithStringArgument() {
            // Arrange
            ModelErrorCollection collection = new ModelErrorCollection();

            // Act
            collection.Add("some message");

            // Assert
            Assert.AreEqual(1, collection.Count);
            ModelError modelError = collection[0];
            Assert.AreEqual("some message", modelError.ErrorMessage);
            Assert.IsNull(modelError.Exception);
        }
        public void AddWithExceptionArgument() {
            // Arrange
            ModelErrorCollection collection = new ModelErrorCollection();
            Exception ex = new Exception("some message");

            // Act
            collection.Add(ex);

            // Assert
            Assert.AreEqual(1, collection.Count);
            ModelError modelError = collection[0];
            Assert.AreSame(ex, modelError.Exception);
        }
Example #39
0
        //error related extensions
        public static ModelErrorCollection GetModelErrors(this Controller controller)
        {
            ModelErrorCollection errors = new ModelErrorCollection();

            foreach (ModelState modelState in controller.ViewData.ModelState.Values)
            {
                foreach (ModelError error in modelState.Errors)
                {
                    errors.Add(error);
                }
            }

            return errors;
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="Radischevo.Wahha.Web.Mvc.ModelStateCollection"/> class.
		/// </summary>
        public ModelStateCollection()
        {
            _errors = new ModelErrorCollection();
        }
 private static bool IsErrorAvalilableIn(ModelErrorCollection errors, string errorMessage)
 {
     return errors.Any(error => error.ErrorMessage == errorMessage);
 }
 public FormFactoryModelStateErrorsWrapper(ModelErrorCollection errors)
     :base(Transform(errors))
 {
     
 }
        private void DoDateAndTimeValidation(AppointmentViewModel viewModel, DateTime localNow, int? excludeAppointmentId)
        {
            if (viewModel.LocalDateTime != viewModel.LocalDateTime.Date)
                throw new ArgumentException("viewModel.Date must be the date alone, without time data.");

            var inconsistencyMessages = new ModelStateDictionary();
            if (!string.IsNullOrEmpty(viewModel.Start) && !string.IsNullOrEmpty(viewModel.End))
            {
                var startTimeLocal = viewModel.LocalDateTime + DateTimeHelper.GetTimeSpan(viewModel.Start);
                var endTimeLocal = viewModel.LocalDateTime + DateTimeHelper.GetTimeSpan(viewModel.End);

                var startTimeUtc = ConvertToUtcDateTime(this.DbPractice, startTimeLocal);
                var endTimeUtc = ConvertToUtcDateTime(this.DbPractice, endTimeLocal);

                var isTimeAvailable = IsTimeAvailableUtc(startTimeUtc, endTimeUtc, this.Doctor.Appointments, excludeAppointmentId);
                if (!isTimeAvailable)
                {
                    inconsistencyMessages.AddModelError(
                        () => viewModel.LocalDateTime,
                        "A data e hora já está marcada para outro compromisso.");
                }
            }

            // Setting the error message to display near the date and time configurations.
            var emptyErrors = new ModelErrorCollection();
            var errorsList = new List<ModelError>();
            errorsList.AddRange(this.ModelState.GetPropertyErrors(() => viewModel.LocalDateTime) ?? emptyErrors);
            errorsList.AddRange(this.ModelState.GetPropertyErrors(() => viewModel.Start) ?? emptyErrors);
            errorsList.AddRange(this.ModelState.GetPropertyErrors(() => viewModel.End) ?? emptyErrors);

            // Flag that tells whether the time and date are valid ot not.
            viewModel.DateAndTimeValidationState =
                errorsList.Any() ? DateAndTimeValidationState.Failed :
                !inconsistencyMessages.IsValid ? DateAndTimeValidationState.Warning :
                DateAndTimeValidationState.Passed;

            // Continue filling error list with warnings.
            errorsList.AddRange(inconsistencyMessages.GetPropertyErrors(() => viewModel.LocalDateTime) ?? emptyErrors);
            errorsList.AddRange(inconsistencyMessages.GetPropertyErrors(() => viewModel.Start) ?? emptyErrors);
            errorsList.AddRange(inconsistencyMessages.GetPropertyErrors(() => viewModel.End) ?? emptyErrors);
            if (errorsList.Any())
            {
                viewModel.TimeValidationMessage = errorsList.First().ErrorMessage;
            }
        }
Example #44
0
        protected ModelErrorCollection GetErrors(ModelStateDictionary modelStateDictionary)
        {
            ModelErrorCollection errors = new ModelErrorCollection();
            foreach (KeyValuePair<string, ModelState> pair in modelStateDictionary)
            {
                foreach (ModelError error in pair.Value.Errors)
                {
                    errors.Add(error);
                }
            }

            return errors;
        }
Example #45
0
 static bool IsErrorAvalilableIn(ModelErrorCollection errors, string errorMessage)
 {
     foreach (var error in errors)
         if (error.ErrorMessage == errorMessage)
             return true;
     return false;
 }
Example #46
0
 /// <summary>
 /// Convert MVC model errors into a single string
 /// </summary>
 /// <param name="errors">MVC model error collection</param>
 /// <returns>Comma separated string containing all errors.</returns>
 protected string ModelErrorString(ModelErrorCollection errors)
 {
     var messages = errors.Select(e => e.ErrorMessage);
     return String.Join(", ", messages);
 }
Example #47
0
 public PropertyError()
 {
     Errors = new ModelErrorCollection();
     Properties = new Dictionary<string, PropertyError>();
     Indexes = new Dictionary<int, PropertyError>();
 }