Exemplo n.º 1
0
        /// <inheritdoc />
        public virtual TagBuilder GenerateLabel(ViewContext viewContext, string fullName, Column column, string labelText, object htmlAttributes)
        {
            if (viewContext == null)
            {
                throw new ArgumentNullException(nameof(viewContext));
            }

            if (column == null)
            {
                throw new ArgumentNullException(nameof(column));
            }

            var resolvedLabelText = labelText;

            if (string.IsNullOrEmpty(resolvedLabelText))
            {
                resolvedLabelText = column.DisplayName;
            }
            if (string.IsNullOrEmpty(resolvedLabelText))
            {
                resolvedLabelText = column.Name;
            }

            var tagBuilder = new TagBuilder("label");
            var idString   = NameAndIdProvider.CreateSanitizedId(viewContext, fullName, IdAttributeDotReplacement);

            tagBuilder.Attributes.Add("for", idString);
            tagBuilder.InnerHtml.SetContent(resolvedLabelText);
            tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes), replaceExisting: true);

            return(tagBuilder);
        }
Exemplo n.º 2
0
        public static TagBuilder GenerateCheckboxBoolean(ViewContext viewContext, ModelExplorer modelExplorer, string expression, string text, bool?isChecked, object divHtmlAttributes, object inputHtmlAttributes, object labelHtmlAttributes)
        {
            var htmlGenerator = viewContext.HttpContext.RequestServices.GetRequiredService <IHtmlGenerator>();

            var div = new TagBuilder("div");

            div.MergeAttributes(GetHtmlAttributeDictionaryOrNull(divHtmlAttributes));

            var name = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);
            var id   = NameAndIdProvider.CreateSanitizedId(viewContext, name, htmlGenerator.IdAttributeDotReplacement);

            var input = htmlGenerator.GenerateCheckBox(viewContext, modelExplorer, expression, isChecked, inputHtmlAttributes);

            //var checkboxHtml = htmlHelper.CheckBox(expression, isChecked, htmlAttributes).Render().Replace("true", value);

            var label = new TagBuilder("label");

            label.MergeAttributes(GetHtmlAttributeDictionaryOrNull(labelHtmlAttributes));
            label.InnerHtml.AppendHtml(text);

            div.InnerHtml.AppendHtml(input);
            if (!string.IsNullOrEmpty(text))
            {
                div.InnerHtml.AppendHtml(label);
            }

            return(div);
        }
Exemplo n.º 3
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            context.ThrowIfNull();
            output.ThrowIfNull();

            var kvList          = Data.GetKeyValueList();
            var selectListItems = kvList.Select(a => new SelectListItem {
                Text = a.Key, Value = a.Value.ToString(), Selected = a.Value == (int)(For.Model ?? -1)
            }).ToList();

            if (!DefaultText.IsNullOrEmpty())
            {
                selectListItems.Insert(0, new SelectListItem {
                    Text = DefaultText, Value = ""
                });
            }
            var tagBuilder = _generator.GenerateSelect(ViewContext, For.ModelExplorer, null, For.Name, selectListItems, null, false, null);

            output.Content.AppendHtml(tagBuilder);
            output.TagName = "div";
            output.TagMode = TagMode.StartTagAndEndTag;
            output.Attributes.Add("class", InputDisplay.GetDisplayName());

            var idStr = NameAndIdProvider.CreateSanitizedId(ViewContext, For.Name,
                                                            _generator.IdAttributeDotReplacement);

            if (Data == null && !Url.IsNullOrEmpty())
            {
                output.PostElement.SetHtmlContent(string.Format(@"<script type='text/javascript'>
                 $(function () {{
                    $('#{0}').bindSelectData('{1}','{2}');
                    }});
                </script>", idStr, Url, For.Model));
            }
        }
Exemplo n.º 4
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            context.ThrowIfNull();
            output.ThrowIfNull();

            var selectListItems = new List <SelectListItem>();
            var kvList          = For?.Metadata.EnumGroupedDisplayNamesAndValues;

            if (kvList != null)
            {
                selectListItems = For.Metadata.EnumGroupedDisplayNamesAndValues.Select(a => new SelectListItem {
                    Text = a.Key.Name.ToString(), Value = a.Value.ToString(), Selected = a.Value == ((int)((For.Model) ?? -1)).ToString()
                }).ToList();
            }

            if (kvList == null && Data != null)
            {
                selectListItems = (List <SelectListItem>)Data;
            }

            var idStr = NameAndIdProvider.CreateSanitizedId(ViewContext, For.Name, _generator.IdAttributeDotReplacement);

            var tagBuilder = new StringBuilder(32);

            selectListItems.ForEach(item =>
            {
                var attributes = new Dictionary <string, object>
                {
                    { "title", item.Text },
                    { "lay-skin", "primary" }
                };
                var inputTagBuilder = _generator.GenerateCheckBox(ViewContext,
                                                                  For.ModelExplorer,
                                                                  For.Name,
                                                                  item.Value == (string)For.ModelExplorer.Model,
                                                                  attributes);
                tagBuilder.Append(inputTagBuilder.GetString());
            });

            var outpuHtml = $@"
              <label class='layui-form-label'>{Text ?? For.Metadata.DisplayName}</label>
            <div id='{idStr}_checkGroup' class='layui-input-block'>
              {tagBuilder}
            </div>";

            output.TagName = "div";
            output.TagMode = TagMode.StartTagAndEndTag;
            output.Attributes.Add("class", InputDisplay.GetDisplayName());
            output.Attributes.Add("id", $"{idStr}_div");
            output.Content.SetHtmlContent(outpuHtml);
            if (kvList == null && !Url.IsNullOrEmpty())
            {
                output.PostElement.SetHtmlContent($@"<script type='text/javascript'>
                 $(function () {{
                    $('#{idStr}_checkGroup').bindCheckBoxData('{Url}','{For.Model}','{For.Name}');
                    }});
                </script>");
            }
        }
        /// Computes the variant to be unique for each radiobutton.
        private string VariantId(KeyValuePair <string, string> enumItem)
        {
            var fullHtmlFieldName = NameAndIdProvider.GetFullHtmlFieldName(ViewContext, For.Name);

            return(new StringBuilder()
                   .Append(NameAndIdProvider.CreateSanitizedId(ViewContext, fullHtmlFieldName, _generator.IdAttributeDotReplacement))
                   .Append(_generator.IdAttributeDotReplacement)
                   .Append(enumItem.Key)
                   .ToString());
        }
Exemplo n.º 6
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            context.ThrowIfNull();
            output.ThrowIfNull();

            var modelExplorer = For.ModelExplorer;
            var attributes    = new Dictionary <string, object>
            {
                { PlaceholderAttributeName, Placeholder ?? modelExplorer.Metadata.Description ?? modelExplorer.Metadata.DisplayName },
                { "class", "layui-input" }
            };

            if (modelExplorer.Metadata != null && modelExplorer.Metadata.IsRequired)
            {
                attributes["required"] = "required";
            }

            var value = modelExplorer.Model ?? Value;

            if (value is DateTime)
            {
                value = ((DateTime)value).ToString(FormatByType(DateTimeType));
            }
            var inputTagBuilder = _generator.GenerateTextBox(ViewContext,
                                                             modelExplorer,
                                                             For.Name,
                                                             value,
                                                             Format,
                                                             attributes);

            output.TagName = "div";
            output.TagMode = TagMode.StartTagAndEndTag;
            output.Content.SetHtmlContent(inputTagBuilder);
            output.Attributes.Add("class", InputDisplay.GetDisplayName());

            var dateTimeTypeStr = DateTimeType.ToString();
            var idStr           = NameAndIdProvider.CreateSanitizedId(ViewContext, For.Name,
                                                                      _generator.IdAttributeDotReplacement);

            output.PostElement.SetHtmlContent(string.Format(@"<script type='text/javascript'>
             layui.use('laydate',
                    function () {{
                        var laydate = layui.laydate;
                        laydate.render({{
                            elem: '#{0}',
                            type: '{1}'
                        }});
                    }});
            </script>", idStr, dateTimeTypeStr));
        }
Exemplo n.º 7
0
        public string GetDomId()
        {
            if (Id != null)
            {
                return(Id);
            }

            if (Name != null)
            {
                return(NameAndIdProvider.CreateSanitizedId(ViewContext, Name, "_"));
            }

            return(null);
        }
Exemplo n.º 8
0
        protected virtual void ExtractFromModelExpression()
        {
            if (ModelExpression != null)
            {
                var modelExplorer = ModelExpression.ModelExplorer;
                var expression    = ModelExpression.Name;
                var name          = NameAndIdProvider.GetFullHtmlFieldName(ViewContext, expression);

                if (Id == null)
                {
                    Id = NameAndIdProvider.CreateSanitizedId(ViewContext, name, "_");
                }

                if (Name == null)
                {
                    Name = name;
                }

                if (Label == null)
                {
                    var label = modelExplorer.Metadata.DisplayName ?? modelExplorer.Metadata.PropertyName;
                    if (label == null && expression != null)
                    {
                        var index = expression.LastIndexOf('.');
                        if (index == -1)
                        {
                            // Expression does not contain a dot separator.
                            label = expression;
                        }
                        else
                        {
                            label = expression.Substring(index + 1);
                        }
                    }
                    Label = label;
                }

                if (Description == null)
                {
                    Description = modelExplorer.Metadata.Description;
                }

                if (modelExplorer.Metadata.ValidatorMetadata.Any(attribute => attribute is RequiredAttribute))
                {
                    Required = true;
                }
            }
        }
Exemplo n.º 9
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            if (this.Id != null)
            {
                if (this.Id.Metadata == null)
                {
                    throw new ArgumentException(nameof(Id));
                }

                string idFieldName  = NameAndIdProvider.GetFullHtmlFieldName(ViewContext, this.Id.Name);
                string idFieldValue = NameAndIdProvider.CreateSanitizedId(this.ViewContext, idFieldName, _generator.IdAttributeDotReplacement);

                output.Attributes.SetAttribute("id", idFieldValue);
            }
        }
Exemplo n.º 10
0
        public static TagBuilder GenerateCheckboxValueButton(ViewContext viewContext, ModelExplorer modelExplorer, string expression, string value, string text, bool?isChecked, object inputHtmlAttributes, object labelHtmlAttributes)
        {
            var htmlGenerator = viewContext.HttpContext.RequestServices.GetRequiredService <IHtmlGenerator>();
            var name          = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);
            var id            = NameAndIdProvider.CreateSanitizedId(viewContext, name, htmlGenerator.IdAttributeDotReplacement);

            var input = new TagBuilder("input");

            input.MergeAttributes(GetHtmlAttributeDictionaryOrNull(inputHtmlAttributes));
            input.MergeAttribute("autocomplete", "off", false);
            input.MergeAttribute("id", id, true);
            input.MergeAttribute("name", name, false);
            input.MergeAttribute("type", "checkbox", true);
            input.MergeAttribute("value", value, false);

            if (modelExplorer != null)
            {
                if (modelExplorer.Model != null)
                {
                    isChecked = string.Equals(modelExplorer.Model.ToString(), value, StringComparison.Ordinal);
                }
            }

            if (GetModelStateValue(viewContext, name, typeof(string[])) is string[] modelStateValues)
            {
                isChecked = modelStateValues.Any(v => string.Equals(v, value, StringComparison.Ordinal));
            }
            else if (GetModelStateValue(viewContext, name, typeof(string)) is string modelStateValue)
            {
                isChecked = string.Equals(modelStateValue, value, StringComparison.Ordinal);
            }

            if (isChecked.HasValue && isChecked.Value)
            {
                input.MergeAttribute("checked", "checked");
            }

            //var checkboxHtml = htmlHelper.CheckBox(expression, isChecked, htmlAttributes).Render().Replace("true", value);

            var label = new TagBuilder("label");

            label.MergeAttributes(GetHtmlAttributeDictionaryOrNull(labelHtmlAttributes));
            label.MergeAttribute("class", "btn btn-outline-secondary mr-2 mb-2 btn-sm", false);

            if (isChecked.HasValue && isChecked.Value)
            {
                label.AddCssClass("active");
            }
            label.InnerHtml.AppendHtml(input);
            label.InnerHtml.AppendHtml(text);

            // If there are any errors for a named field, we add the CSS attribute.
            if (viewContext.ViewData.ModelState.TryGetValue(name, out var entry) && entry.Errors.Count > 0)
            {
                input.AddCssClass(HtmlHelper.ValidationInputCssClassName);
            }

            AddValidationAttributes(viewContext, input, modelExplorer, expression);

            return(label);
        }
Exemplo n.º 11
0
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            if (For == null)
            {
                throw new ArgumentNullException(nameof(For));
            }

            output.TagName = "label";
            TagBuilder tagBuilder = new TagBuilder("label");
            bool       isRequired = Required ?? For.Metadata.AdditionalValues.TryGetValue("PLRequired", out _);

            if (isRequired)
            {
                tagBuilder.MergeAttribute("class", "label-required");
                tagBuilder.MergeAttribute("title", _localizer["Yêu cầu nhập."]);
            }

            string fullName = NameAndIdProvider.GetFullHtmlFieldName(ViewContext, For.Name);
            string idString = NameAndIdProvider.CreateSanitizedId(ViewContext, fullName, optionsAccessor.Value.HtmlHelperOptions.IdAttributeDotReplacement);

            tagBuilder.Attributes.Add("for", idString);

            string labelText = For.ModelExplorer.Metadata.DisplayName ?? For.Name ?? For.ModelExplorer.Metadata.PropertyName;

            tagBuilder.InnerHtml.SetContent(labelText);

            if (!string.IsNullOrEmpty(DisplayHint))
            {
                TagBuilder builder = new TagBuilder("i");
                builder.MergeAttribute("class", "fa fa-question-circle info hellp-hit");
                builder.MergeAttribute("data-toggle", "tooltip");
                builder.MergeAttribute("data-placement", "top");
                builder.MergeAttribute("title", DisplayHint);
                tagBuilder.InnerHtml.AppendHtml(builder);
            }

            output.MergeAttributes(tagBuilder);
            if (!output.IsContentModified)
            {
                TagHelperContent childContent = await output.GetChildContentAsync();

                if (childContent.IsEmptyOrWhiteSpace)
                {
                    if (tagBuilder.HasInnerHtml)
                    {
                        output.Content.SetHtmlContent(tagBuilder.InnerHtml);
                    }
                }
                else
                {
                    output.Content.SetHtmlContent(childContent);
                }
            }
        }
Exemplo n.º 12
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            context.ThrowIfNull();
            output.ThrowIfNull();

            var modelExplorer = For.ModelExplorer;

            var attributes = new Dictionary <string, object>
            {
                { PlaceholderAttributeName, Placeholder },
                { TextAttributeName, Text ?? modelExplorer.Metadata.Description ?? modelExplorer.Metadata.DisplayName },
                { "class", "layui-input" }
            };

            if (Disabled)
            {
                attributes["Disabled"] = "Disabled";
            }

            var value = modelExplorer.Model ?? Value;

            var htmlText  = !attributes[TextAttributeName].ToStr().IsNullOrWhiteSpace() ? $"<label class='layui-form-label'>{attributes[TextAttributeName]}</label>" : "";
            var outpuHtml = $@"
                    {htmlText}
                    <div class='layui-input-inline'>
                        <button id='btn_{For.Name}_up' type='button' class='layui-btn' >上传图片</button>
                <img class='layui-upload-img' id='{For.Name}_imgs1' src='{value}' style='max-width:200px' />
                <p id='{For.Name}_retry'></p>
                <input  id='{For.Name}_imgs2' type = 'hidden' value='{value}' name='{For.Name}'>
                <div>请上传100px*100px的图片</div>
                    </div>";

            var idStr = NameAndIdProvider.CreateSanitizedId(ViewContext, For.Name, _generator.IdAttributeDotReplacement);

            output.TagName = "div";
            output.TagMode = TagMode.StartTagAndEndTag;
            output.Attributes.Add("class", "layui-form-item");
            output.Attributes.Add("id", $"{idStr}_div");
            output.Content.SetHtmlContent(outpuHtml);

            output.PostElement.SetHtmlContent($@" <script type='text/javascript'>
$(function () {{
                var imageUrl;
            var $ = layui.jquery;
            var upload = layui.upload;

            var uploadInst = upload.render({{
                elem: '#btn_{For.Name}_up',
                url: '/Upload/Img',
                before: function (obj) {{
                    obj.preview(function (index, file, result) {{
                        if (file.size / 1024 / 1024 > 2) {{
                            layer.msg('上传的图片不能超过1M',
                            {{
                                icon: 2,
                                time: 2000
                            }});
                            return false;
                        }}
                        $('#{For.Name}_imgs1').attr('src', result);
                    }});
                }},
                done: function (res) {{
                    if (res.success) {{
                        if (res.data) {{
                            imageUrl = res.data;
                                $('#{For.Name}_imgs2').val(imageUrl);
                        }}
                    }} else {{
                        var demoText = $('#{For.Name}_retry');
                        demoText.html(""<span style='color: #FF5722;'>上传失败</span> <a class='layui-btn layui-btn-xs demo-reload'>重试</a>"");
                        demoText.find('.demo-reload').on('click', function () {{
                            uploadInst.upload();
                        }});
                    }}
                }}
            }});
            }});
            </script>");
        }
Exemplo n.º 13
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            context.ThrowIfNull();
            output.ThrowIfNull();

            var selectListItems = new List <SelectListItem>();
            var kvList          = For?.Metadata.EnumGroupedDisplayNamesAndValues;

            if (kvList != null)
            {
                selectListItems = For.Metadata.EnumGroupedDisplayNamesAndValues.Select(a => new SelectListItem
                {
                    Text  = a.Key.Name.ToString(),
                    Value = a.Value.ToString()
                }).ToList();
            }

            if (kvList == null && Data != null)
            {
                selectListItems = ((IEnumerable <SelectListItem>)Data).ToList();
            }

            if (!DefaultText.IsNullOrWhiteSpace())
            {
                selectListItems.Insert(0, new SelectListItem {
                    Text = DefaultText, Value = ""
                });
            }

            var idStr      = NameAndIdProvider.CreateSanitizedId(ViewContext, For.Name, _generator.IdAttributeDotReplacement);
            var attributes = new Dictionary <string, object>
            {
                { "xm-select", idStr },
                { "xm-select-skin", "default" }
            };

            IList l = new ArrayList();

            if (For.Model != null)
            {
                l = (IList)For.Model;
            }

            selectListItems.ForEach(item =>
            {
                item.Selected = For.Model != null && l.Contains(item.Value);
            });

            var tagBuilder = _generator.GenerateSelect(ViewContext, For.ModelExplorer, null, For.Name, selectListItems, null, false, attributes);

            var outpuHtml = $@"
              <label class='layui-form-label'>{Text ?? For.Metadata.DisplayName}</label>
            <div class='layui-input-block'>
              {tagBuilder.GetString().Replace("&amp;nbsp;", "&nbsp;")}
            </div>";

            output.TagName = "div";
            output.TagMode = TagMode.StartTagAndEndTag;
            output.Attributes.Add("id", $"{idStr}_div");
            output.Attributes.Add("class", InputDisplay.GetDisplayName());
            output.Content.SetHtmlContent(outpuHtml);

            var jsValue = l.Cast <object>().Aggregate("", (current, t) => current + (t + ",")).TrimEnd(',');

            if (kvList == null && !Url.IsNullOrEmpty())
            {
                output.PostElement.SetHtmlContent($@"<script type='text/javascript'>
                 $(function () {{
                    $('#{idStr}').bindMultiSelectData('{Url}','{jsValue}','{idStr}');
                    }});
                </script>");
            }
        }