Esempio n. 1
0
        private MvcHtmlString LabelFor <TValue>(Expression <Func <TModel, TValue> > expression, object htmlAttributes = null, string expressionTypeName = null)
        {
            var modelMetadata  = ModelMetadata.FromLambdaExpression(expression, _htmlHelper.ViewData);
            var expressionText = GetExpressionText(expression);
            var labelText      = LabelText(modelMetadata, expressionText);

            if (string.IsNullOrEmpty(labelText))
            {
                return(MvcHtmlString.Empty);
            }

            if (string.IsNullOrEmpty(expressionTypeName))
            {
                expressionTypeName = GetExpressionTypeName(expression);
            }

            var templateInfo = _htmlHelper.ViewContext.ViewData.TemplateInfo;

            if (!string.IsNullOrEmpty(expressionTypeName))
            {
                templateInfo.HtmlFieldPrefix = expressionTypeName;
            }

            var @for = templateInfo.GetFullHtmlFieldId(expressionText);

            var labelTag = new TagBuilder("label");

            labelTag.MergeAttributes(RouteValueDictionaryExtensions.Convert(htmlAttributes));
            labelTag.Attributes.Add("for", Sanitizer.Slug(@for));
            labelTag.SetInnerText(labelText);

            return(MvcHtmlString.Create(labelTag.ToString(TagRenderMode.Normal)));
        }
Esempio n. 2
0
        private MvcHtmlString TextAreaHelper(ModelMetadata modelMetadata, string name, IDictionary <string, object> rowsAndColumns, object htmlAttributes, string expressionTypeName = null)
        {
            var templateInfo = _htmlHelper.ViewContext.ViewData.TemplateInfo;

            if (!string.IsNullOrEmpty(expressionTypeName))
            {
                templateInfo.HtmlFieldPrefix = expressionTypeName;
            }

            var fullName = templateInfo.GetFullHtmlFieldName(name);

            var textAreaTag = new TagBuilder("textarea");

            textAreaTag.MergeAttribute("id", Sanitizer.Slug(fullName));
            textAreaTag.MergeAttributes(RouteValueDictionaryExtensions.Convert(htmlAttributes), true);
            textAreaTag.MergeAttributes(rowsAndColumns, rowsAndColumns != null);
            textAreaTag.MergeAttribute("name", fullName, true);

            ModelState modelState;

            _htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState);

            var unobtrusiveValidationAttributes = _htmlHelper.GetUnobtrusiveValidationAttributes(name);

            textAreaTag.MergeAttributes(unobtrusiveValidationAttributes);

            string value;

            if (modelState != null && modelState.Value != null)
            {
                value = modelState.Value.AttemptedValue;
            }
            else if (modelMetadata.Model != null)
            {
                value = modelMetadata.Model.ToString();
            }
            else
            {
                value = string.Empty;
            }

            textAreaTag.SetInnerText(value);

            return(textAreaTag.ToMvcHtmlString(TagRenderMode.Normal));
        }
Esempio n. 3
0
        public static void InjectMessages(this ModelStateDictionary modelStateDictionary, ServiceOperationResult serviceOperationResult)
        {
            foreach (var errorMessage in serviceOperationResult.Errors)
            {
                if (string.IsNullOrEmpty(errorMessage.Key))
                {
                    modelStateDictionary.AddModelError("", errorMessage.Value);
                    continue;
                }

                var key = Sanitizer.Slug(errorMessage.Key);

                var modelError = modelStateDictionary.Keys.Where(k => k.EndsWith(key)).OrderBy(k => k.Length).FirstOrDefault();

                if (modelError == null)
                {
                    return;
                }

                modelStateDictionary[modelError].Errors.Add(errorMessage.Value);
            }
        }
Esempio n. 4
0
        private static string CreateSubPropertyName(string propertyName)
        {
            propertyName = Sanitizer.Slug(propertyName);

            return(propertyName);
        }
Esempio n. 5
0
        protected static string GetExpressionText <TProperty, TModel>(Expression <Func <TModel, TProperty> > expression)
        {
            var expressionText = ExpressionHelper.GetExpressionText(expression);

            return(Sanitizer.Slug(expressionText));
        }
Esempio n. 6
0
        private MvcHtmlString ValidationMessageHelper(ModelMetadata modelMetadata, string expression, string validationMessage, IDictionary <string, object> htmlAttributes, out bool hasError, string expressionTypeName = null)
        {
            hasError = false;

            var formContext  = _htmlHelper.ViewContext.FormContext;
            var templateInfo = _htmlHelper.ViewContext.ViewData.TemplateInfo;

            if (!string.IsNullOrEmpty(expressionTypeName))
            {
                templateInfo.HtmlFieldPrefix = expressionTypeName;
            }

            var fullName = templateInfo.GetFullHtmlFieldName(expression);

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

            var modelState  = _htmlHelper.ViewData.ModelState[fullName];
            var modelErrors = (modelState == null) ? null : modelState.Errors;
            var modelError  = (((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors.FirstOrDefault(me => !string.IsNullOrEmpty(me.ErrorMessage)) ?? modelErrors[0]);

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

            var builder = new TagBuilder("span");

            builder.AddCssClass("help-inline");
            builder.MergeAttributes(htmlAttributes);

            if (!string.IsNullOrEmpty(validationMessage))
            {
                builder.SetInnerText(validationMessage);
                hasError = true;
            }
            else if (modelError != null)
            {
                builder.SetInnerText(GetUserErrorMessageOrDefault(_htmlHelper.ViewContext.HttpContext, modelError, modelState));
                hasError = true;
            }

            if (formContext != null)
            {
                var replaceValidationMessageContents = string.IsNullOrEmpty(validationMessage);

                if (_htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled)
                {
                    builder.MergeAttribute("data-valmsg-for", fullName);
                    builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant());
                }
                else
                {
                    var fieldMetadata = ApplyFieldValidationMetadata(_htmlHelper, modelMetadata, fullName);

                    fieldMetadata.ReplaceValidationMessageContents = replaceValidationMessageContents;

                    builder.MergeAttribute("id", Sanitizer.Slug(fullName + "ValidationMessage"));
                    fieldMetadata.ValidationMessageId = builder.Attributes["id"];
                }
            }

            return(builder.ToMvcHtmlString(TagRenderMode.Normal));
        }
Esempio n. 7
0
        private MvcHtmlString InputHelper(InputType inputType, ModelMetadata modelMetadata, string name, object value, bool useViewData, bool isChecked, bool setId, bool isExplicitValue, object htmlAttributes, string expressionTypeName = null)
        {
            var templateInfo = _htmlHelper.ViewContext.ViewData.TemplateInfo;

            if (!string.IsNullOrEmpty(expressionTypeName))
            {
                templateInfo.HtmlFieldPrefix = expressionTypeName;
            }

            var fullName = templateInfo.GetFullHtmlFieldName(name);

            var tagBuilder = new TagBuilder("input");

            tagBuilder.MergeAttributes(RouteValueDictionaryExtensions.Convert(htmlAttributes));
            tagBuilder.MergeAttribute("type", HtmlHelper.GetInputTypeString(inputType));
            tagBuilder.MergeAttribute("name", fullName, true);

            var valueParameter = Convert.ToString(value, CultureInfo.CurrentCulture);
            var usedModelState = false;

            switch (inputType)
            {
            case InputType.CheckBox:
                var modelStateWasChecked = GetModelStateValue(fullName, typeof(bool)) as bool?;
                if (modelStateWasChecked.HasValue)
                {
                    isChecked      = modelStateWasChecked.Value;
                    usedModelState = true;
                }
                goto case InputType.Radio;

            case InputType.Radio:
                if (!usedModelState)
                {
                    var modelStateValue = GetModelStateValue(fullName, typeof(string)) as string;
                    if (modelStateValue != null)
                    {
                        isChecked      = string.Equals(modelStateValue, valueParameter, StringComparison.Ordinal);
                        usedModelState = true;
                    }
                }
                if (!usedModelState && useViewData)
                {
                    isChecked = EvalBoolean(fullName);
                }
                if (isChecked)
                {
                    tagBuilder.MergeAttribute("checked", "checked");
                }
                tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);
                break;

            case InputType.Password:
                if (value != null)
                {
                    tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);
                }
                break;

            default:
                var attemptedValue = (string)GetModelStateValue(fullName, typeof(string));
                tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? EvalString(fullName) : valueParameter), isExplicitValue);
                break;
            }

            if (setId)
            {
                tagBuilder.MergeAttribute("id", Sanitizer.Slug(fullName));
            }

            ModelState modelState;

            _htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState);

            var unobtrusiveValidationAttributes = _htmlHelper.GetUnobtrusiveValidationAttributes(name, modelMetadata);

            tagBuilder.MergeAttributes(unobtrusiveValidationAttributes);

            if (inputType == InputType.CheckBox)
            {
                var inputItemBuilder = new StringBuilder();
                inputItemBuilder.Append(tagBuilder.ToString(TagRenderMode.SelfClosing));

                var hiddenInput = new TagBuilder("input");
                hiddenInput.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.Hidden));
                hiddenInput.MergeAttribute("name", fullName);
                hiddenInput.MergeAttribute("value", "false");
                inputItemBuilder.Append(hiddenInput.ToString(TagRenderMode.SelfClosing));
                return(MvcHtmlString.Create(inputItemBuilder.ToString()));
            }

            return(tagBuilder.ToMvcHtmlString(TagRenderMode.SelfClosing));
        }
Esempio n. 8
0
        private MvcHtmlString SelectInternal(ModelMetadata modelMetadata, string optionLabel, string name, IEnumerable <SelectListItem> selectList, bool allowMultiple, object htmlAttributes, string expressionTypeName = null)
        {
            var templateInfo = _htmlHelper.ViewContext.ViewData.TemplateInfo;

            if (!string.IsNullOrEmpty(expressionTypeName))
            {
                templateInfo.HtmlFieldPrefix = expressionTypeName;
            }

            var fullName = templateInfo.GetFullHtmlFieldName(name);

            var usedViewData = false;

            if (selectList == null)
            {
                selectList   = GetSelectData(fullName);
                usedViewData = true;
            }

            var defaultValue = allowMultiple ? GetModelStateValue(fullName, typeof(string[])) : GetModelStateValue(fullName, typeof(string));

            if (!usedViewData)
            {
                if (defaultValue == null)
                {
                    defaultValue = _htmlHelper.ViewData.Eval(fullName);
                }
            }

            if (defaultValue != null)
            {
                var defaultValues = allowMultiple ? defaultValue as IEnumerable : new[] { defaultValue };
                var values        = from object value in defaultValues
                                    select Convert.ToString(value, CultureInfo.CurrentCulture);

                var selectedValues = new HashSet <string>(values, StringComparer.OrdinalIgnoreCase);
                var newSelectList  = new List <SelectListItem>();

                if (selectList != null)
                {
                    foreach (var selectListItem in selectList)
                    {
                        selectListItem.Selected = selectListItem.Value != null?selectedValues.Contains(selectListItem.Value) : selectedValues.Contains(selectListItem.Text);

                        newSelectList.Add(selectListItem);
                    }
                }

                selectList = newSelectList;
            }

            var listItemBuilder = new StringBuilder();

            if (optionLabel != null)
            {
                listItemBuilder.AppendLine(ListItemToOption(new SelectListItem {
                    Text     = optionLabel,
                    Value    = string.Empty,
                    Selected = false
                }));
            }

            if (selectList != null)
            {
                foreach (var item in selectList)
                {
                    listItemBuilder.AppendLine(ListItemToOption(item));
                }
            }

            var tagBuilder = new TagBuilder("select")
            {
                InnerHtml = listItemBuilder.ToString()
            };

            tagBuilder.MergeAttributes(RouteValueDictionaryExtensions.Convert(htmlAttributes));
            tagBuilder.MergeAttribute("name", fullName, true);
            tagBuilder.MergeAttribute("id", Sanitizer.Slug(fullName));
            if (allowMultiple)
            {
                tagBuilder.MergeAttribute("multiple", "multiple");
            }

            ModelState modelState;

            _htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState);

            var unobtrusiveValidationAttributes = _htmlHelper.GetUnobtrusiveValidationAttributes(name, modelMetadata);

            tagBuilder.MergeAttributes(unobtrusiveValidationAttributes);

            return(tagBuilder.ToMvcHtmlString(TagRenderMode.Normal));
        }