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)); } }
protected HtmlString GenerateDropDown(ModelMetadata metadata, string expression, IEnumerable <SelectListItem> selectList, string optionLabel, object htmlAttributes) { var tagBuilder = _htmlGenerator.GenerateSelect( ViewContext, metadata, optionLabel, name: expression, selectList: selectList, allowMultiple: false, htmlAttributes: htmlAttributes); if (tagBuilder == null) { return(HtmlString.Empty); } return(tagBuilder.ToHtmlString(TagRenderMode.Normal)); }
public override void Process(TagHelperContext context, TagHelperOutput output) { using (var writer = new StringWriter()) { writer.Write(@"<div class=""form-group"">"); var label = _generator.GenerateLabel( ViewContext, For.ModelExplorer, For.Name, null, new { @class = "control-label" }); label.WriteTo(writer, NullHtmlEncoder.Default); object htmlAttributes = null; if (Disabled) { htmlAttributes = new { @class = "form-control", @disabled = "disabled" }; } else { htmlAttributes = new { @class = "form-control" }; } var selectList = _generator.GenerateSelect( ViewContext, For.ModelExplorer, "---", For.Name, ItemList, false, htmlAttributes); selectList.WriteTo(writer, NullHtmlEncoder.Default); var validationMsg = _generator.GenerateValidationMessage( ViewContext, For.ModelExplorer, For.Name, null, ViewContext.ValidationMessageElement, new { @class = "text-danger" }); validationMsg.WriteTo(writer, NullHtmlEncoder.Default); writer.Write(@"</div>"); output.Content.SetHtmlContent(writer.ToString()); } }
protected IHtmlContent GenerateDropDown( ModelExplorer modelExplorer, string expression, IEnumerable <SelectListItem> selectList, string optionLabel, object htmlAttributes) { var tagBuilder = _htmlGenerator.GenerateSelect( ViewContext, modelExplorer, optionLabel, expression, selectList, allowMultiple: false, htmlAttributes: htmlAttributes); if (tagBuilder == null) { return(HtmlString.Empty); } return(tagBuilder); }
private async Task <TagBuilder> BuildSelect() { var containerType = For.Metadata.ContainerType; var property = containerType.GetProperty(For.Metadata.PropertyName); var dropDownListAttribute = property.GetCustomAttribute <SelectListAttribute>(); var items = await dropDownListAttribute.GetOptions(_dbContext); var currentValue = ((IEntity)For.Model)?.Id.ToString(); var tagBuilder = _generator.GenerateSelect(ViewContext, For.ModelExplorer, null, For.Name, items, new List <string> { currentValue }, false, new { @class = "form-control" }); return(tagBuilder); }
/// <summary> /// Synchronously executes the <see cref="TagHelper" /> with the given <paramref name="context" /> and /// <paramref name="output" />. /// </summary> /// <param name="context">Contains information associated with the current HTML tag.</param> /// <param name="output">A stateful HTML element used to generate an HTML tag.</param> public override void Process(TagHelperContext context, TagHelperOutput output) { // Generate the list. var selectListItems = GenerateListForEnumType(); // Get current value for model expression. var currentValues = Generator.GetCurrentValues(ViewContext, EnumFor.ModelExplorer, EnumFor.Name, false); var tag = Generator.GenerateSelect(ViewContext, EnumFor?.ModelExplorer, null, EnumFor?.Name, selectListItems, currentValues, false, null); if (tag != null) { output.MergeAttributes(tag); output.PostContent.AppendHtml(tag.InnerHtml); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { var ddType = output.TagName.Split("-")[1]; output.TagName = string.Empty; if (ddType.Equals("simple") || !(For.ModelExplorer.ModelType.IsGenericType && For.ModelExplorer.ModelType.GetGenericTypeDefinition() == typeof(List <>))) { AllowMultiple = false; } var htmlAttributes = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase) { { "name", For.Name }, { "class", "form-control" } }; for (int i = 0; i < output.Attributes.Count; i++) { var item = output.Attributes[i]; if (!htmlAttributes.ContainsKey(item.Name)) { htmlAttributes.Add(item.Name, item.Value); } } var inputTag = _htmlGenerator.GenerateSelect(Context, For.ModelExplorer, null, For.Name, Items, AllowMultiple, htmlAttributes); output.Content.AppendHtml(inputTag); var script = $@"$(function () {{ $('#{inputTag.Attributes["id"]}').select2({{ placeholder: '{Default_Select}', theme: 'bootstrap4', width: 'resolve', minimumResultsForSearch: -1 }}); }}); "; _scriptHelper.AddScriptText(script); }
void BuildInputType(PropertyInfo prop, FormGroupModel group, ModelExplorer modelExplorer) { //判断是否有设置dataType var dataType = prop.GetCustomAttribute <DataTypeAttribute>(); if (dataType?.DataType != null) { switch (dataType.DataType) { case DataType.Text: group.Input = Generator.GenerateTextBox(viewContext, modelExplorer, prop.Name, null, null, new { @class = "form-control" }); group.TextDanger = Generator.GenerateValidationMessage(viewContext, modelExplorer, prop.Name, null, viewContext.ValidationMessageElement, new { @class = "text-danger" }); break; case DataType.Password: group.Input = Generator.GeneratePassword(viewContext, modelExplorer, prop.Name, null, new { @class = "form-control" }); group.TextDanger = Generator.GenerateValidationMessage(viewContext, modelExplorer, prop.Name, null, viewContext.ValidationMessageElement, new { @class = "text-danger" }); break; case DataType.PhoneNumber: group.Input = Generator.GenerateTextBox(viewContext, modelExplorer, prop.Name, null, null, new { @class = "form-control", @type = "tel" }); group.TextDanger = Generator.GenerateValidationMessage(viewContext, modelExplorer, prop.Name, null, viewContext.ValidationMessageElement, new { @class = "text-danger" }); break; case DataType.MultilineText: group.Input = Generator.GenerateTextArea(viewContext, modelExplorer, prop.Name, 2, 1, new { @class = "form-control" }); group.TextDanger = Generator.GenerateValidationMessage(viewContext, modelExplorer, prop.Name, null, viewContext.ValidationMessageElement, new { @class = "text-danger" }); break; case DataType.EmailAddress: group.Input = Generator.GenerateTextBox(viewContext, modelExplorer, prop.Name, null, null, new { @class = "form-control", @type = "email" }); group.TextDanger = Generator.GenerateValidationMessage(viewContext, modelExplorer, prop.Name, null, viewContext.ValidationMessageElement, new { @class = "text-danger" }); break; case DataType.Url: group.Input = Generator.GenerateTextBox(viewContext, modelExplorer, prop.Name, null, null, new { @class = "form-control", @type = "url" }); group.TextDanger = Generator.GenerateValidationMessage(viewContext, modelExplorer, prop.Name, null, viewContext.ValidationMessageElement, new { @class = "text-danger" }); break; default: break; } return; } // 自定义selectControl控件 var selectControl = prop.GetCustomAttribute <SelectControlAttribute>(); if (selectControl != null) { if (selectControl.Type == ItemDataType.StaticItems) { List <SelectListItem> nodes = new List <SelectListItem>(); var items = modelType.GetProperty(selectControl.ItemsName); if (items != null) { nodes = items.GetValue(viewModel.Model, null) as List <SelectListItem>; } group.Input = Generator.GenerateSelect(viewContext, modelExplorer, null, prop.Name, nodes?.ToList(), false, new { @class = "form-control" }); var initValue = nodes.FirstOrDefault(d => d.Selected)?.Value; var ngInit = initValue?.Length > 0 ? initValue : nodes[0].Value; group.Input.Attributes.Add("ng-init", $"Model.Active.{prop.Name}='{ngInit}'"); } else { string url = selectControl.Type == ItemDataType.AbsUrl ? selectControl.Url : $"http://{viewContext.HttpContext.Request.Host.Value}/{selectControl.Controller}/{selectControl.Action}"; group.Input = new TagBuilder("select-control"); group.Input.AddCssClass("form-control"); group.Input.Attributes.Add("id", prop.Name); group.Input.Attributes.Add("name", prop.Name); group.Input.Attributes.Add("request-url", url); group.Input.Attributes.Add("request-init", $"Model.Active.{prop.Name}"); } return; } //自定义 radiolist 控件 //var radioListControl = prop.GetCustomAttribute<RadioListAttribute>(); //if (radioListControl != null) //{ // var values = radioListControl.Values.Split(','); // var tests = radioListControl.Texts.Split(','); // if (values.Length == tests.Length) // { // group.Input = new TagBuilder("div"); // var index = 0; // foreach (var item in values) // { // group.Input = new TagBuilder("label"); // group.Input.InnerHtml.AppendHtml($"<input type='radio' name='{prop.Name}' ng-model='Model.Active.{item}' class='form-control'/>{tests[index++]}"); // } // } // return; //} if (prop.GetType() == typeof(int) || prop.GetType() == typeof(float) || prop.GetType() == typeof(double)) { group.Input = Generator.GenerateTextBox(viewContext, modelExplorer, prop.Name, null, null, new { @class = "form-control", @type = "number" }); } else { group.Input = Generator.GenerateTextBox(viewContext, modelExplorer, prop.Name, null, null, new { @class = "form-control" }); } group.TextDanger = Generator.GenerateValidationMessage(viewContext, modelExplorer, prop.Name, null, viewContext.ValidationMessageElement, new { @class = "text-danger" }); }
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.TryInt().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 = TagBuilder.CreateSanitizedId(For.Name, _generator.IdAttributeDotReplacement); var attributes = new Dictionary <string, object> { { "lay-search", "" }, { "lay-filter", idStr } }; var cValue = For.Metadata.IsEnum ? ((int)(For.Model ?? 0)).ToStr() : For.Model.ToStr(); selectListItems.ForEach(item => { item.Selected = For.Model != null && item.Value == cValue; }); 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("&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); if (kvList == null && !Url.IsNullOrEmpty()) { output.PostElement.SetHtmlContent($@"<script type='text/javascript'> $(function () {{ $('#{idStr}').bindSelectData('{Url}','{For.Model}'); }}); </script>"); } }
private void WriteSelect(IEnumerable <SelectListItem> selectList, TextWriter writer, string expression, ModelExplorer modelExplorer, string placeholder = "-- Välj --", string requiredMessage = null, bool isRequired = true) { if (selectList.FirstOrDefault() is ExtendedSelectListItem) { GenerateExtendedSelectList(writer, selectList, placeholder, modelExplorer); } else { var prefixAttribute = (PrefixAttribute)AttributeHelper.GetAttribute <PrefixAttribute>( For.ModelExplorer.Metadata.ContainerType, For.ModelExplorer.Metadata.PropertyName); bool writePrefix = prefixAttribute != null && prefixAttribute.PrefixPosition == PrefixAttribute.Position.Value; var realModelType = modelExplorer.ModelType; var allowMultiple = typeof(string) != realModelType && typeof(IEnumerable).IsAssignableFrom(realModelType); var currentValues = _htmlGenerator.GetCurrentValues( ViewContext, modelExplorer, expression: expression, allowMultiple: allowMultiple); var tagBuilder = _htmlGenerator.GenerateSelect( ViewContext, modelExplorer, optionLabel: null, expression: expression, selectList: selectList, currentValues: currentValues, allowMultiple: allowMultiple, htmlAttributes: new { @class = "form-control" }); tagBuilder.Attributes.Add("data-placeholder", placeholder); if (requiredMessage != null && isRequired) { tagBuilder.Attributes.Remove("data-val-required"); tagBuilder.Attributes.Add("data-val-required", requiredMessage); } if (!isRequired) { tagBuilder.Attributes.Remove("data-val-required"); } if (For.Model == null) { var existingOptionsBuilder = new HtmlContentBuilder(); tagBuilder.InnerHtml.MoveTo(existingOptionsBuilder); tagBuilder.InnerHtml.Clear(); tagBuilder.InnerHtml.AppendHtml("<option value></option>"); tagBuilder.InnerHtml.AppendHtml(existingOptionsBuilder); } if (writePrefix) { writer.Write("<span class=\"prefix\">"); } WritePrefix(writer, PrefixAttribute.Position.Value); if (writePrefix) { writer.Write("</span>"); } tagBuilder.WriteTo(writer, _htmlEncoder); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { var isLg = output.Attributes.SingleOrDefault(a => a.Name == "lg") != null; var isSm = output.Attributes.SingleOrDefault(a => a.Name == "sm") != null; var isFloating = output.Attributes.SingleOrDefault(a => a.Name == "float") != null; var isDisabled = output.Attributes.SingleOrDefault(a => a.Name == "disabled") != null; var isReadOnly = output.Attributes.SingleOrDefault(a => a.Name == "readonly") != null; var isRequired = output.Attributes.SingleOrDefault(a => a.Name == "required") != null; var hasWarning = output.Attributes.SingleOrDefault(a => a.Name == "has-warning") != null; var hasSuccess = output.Attributes.SingleOrDefault(a => a.Name == "has-success") != null; var hasError = output.Attributes.SingleOrDefault(a => a.Name == "has-error") != null; var icon = output.Attributes.SingleOrDefault(a => a.Name == "icon"); var placeholder = output.Attributes.SingleOrDefault(a => a.Name == "placeholder"); var binding = output.Attributes.SingleOrDefault(a => a.Name == "for"); output.Attributes.RemoveAll("lg"); output.Attributes.RemoveAll("sm"); output.Attributes.RemoveAll("float"); output.Attributes.RemoveAll("disabled"); output.Attributes.RemoveAll("readonly"); output.Attributes.RemoveAll("required"); output.Attributes.RemoveAll("has-warning"); output.Attributes.RemoveAll("has-success"); output.Attributes.RemoveAll("has-error"); output.Attributes.RemoveAll("icon"); output.Attributes.RemoveAll("placeholder"); output.Attributes.RemoveAll("for"); var formGroupClass = "form-group pmd-textfield"; var labelAttributes = new Dictionary <string, object>(); var selectAttributes = new Dictionary <string, object> { { "class", "form-control pmd-select2-tags tags" } }; if (isLg) { formGroupClass = $"{formGroupClass} form-group-lg"; } if (isSm) { formGroupClass = $"{formGroupClass} form-group-sm"; } if (isFloating) { formGroupClass = $"{formGroupClass} pmd-textfield-floating-label"; } if (hasWarning) { formGroupClass = $"{formGroupClass} has-warning"; } if (hasSuccess) { formGroupClass = $"{formGroupClass} has-sucess"; } if (hasError) { formGroupClass = $"{formGroupClass} has-error"; } if (isDisabled) { selectAttributes.Add("disabled", "disabled"); } if (isReadOnly) { selectAttributes.Add("readonly", "readonly"); } if (isRequired) { selectAttributes.Add("required", "required"); } var inputPre = ""; var inputPost = ""; var labelClass = "control-label"; string placeholderString = placeholder != null?placeholder.Value.ToString() : ""; if (icon != null) { inputPre = $"{inputPre}<div class=\"input-group\"><div class=\"input-group-addon\"><i class=\"material-icons md-dark pmd-sm\">{icon.Value}</i></div>"; inputPost = $"{inputPost}</div>"; labelClass = $"{labelClass} pmd-input-group-label"; } labelAttributes.Add("class", labelClass); var metadata = For.Metadata; var modelExplorer = For.ModelExplorer; var items = new List <SelectListItem>(); if (modelExplorer.Model != null) { foreach (var item in (string[])modelExplorer.Model) { items.Add(new SelectListItem() { Text = item, Value = item }); } } var select = _generator.GenerateSelect(ViewContext, modelExplorer, placeholderString, For.Name, items, true, selectAttributes); var label = _generator.GenerateLabel(ViewContext, modelExplorer, For.Name, metadata.DisplayName, labelAttributes); var hidden = _generator.GenerateHidden(ViewContext, modelExplorer, For.Name, null, true, null); output.TagName = "div"; output.TagMode = TagMode.StartTagAndEndTag; output.Attributes.SetAttribute("class", formGroupClass); string selectOutput; using (var writer = new StringWriter()) { label.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default); writer.Write(inputPre); select.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default); writer.Write(inputPost); //hidden.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default); selectOutput = writer.ToString(); } output.Content.SetHtmlContent(selectOutput); }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (context == null || output == null) { throw new ArgumentNullException(); } Contract.EndContractBlock(); var selectDropdownContext = new SelectDropdownContext(); context.Items.Add(typeof(SelectDropdownTagHelper), selectDropdownContext); await output.GetChildContentAsync(); var modelExpression = SelectedValueProperty ?? SelectedIdProperty; var key = modelExpression.Name.ToLower(); var className = $"select2-dropdown-{key}"; var currentValues = _generator.GetCurrentValues(ViewContext, modelExpression.ModelExplorer, modelExpression.Name, false); var selectBuilder = _generator.GenerateSelect(ViewContext, modelExpression.ModelExplorer, null, modelExpression.Name, Enumerable.Empty <SelectListItem>(), currentValues, false, null); if (selectBuilder != null) { var classes = className; if (context.AllAttributes.TryGetAttribute("class", out var classTag)) { classes = $"{classes} {classTag.Value}"; } if (selectBuilder.Attributes.ContainsKey("class")) { selectBuilder.Attributes["class"] = $"{selectBuilder.Attributes["class"]} {classes}"; } else { selectBuilder.Attributes.Add("class", classes); } output.Content.AppendHtml(selectBuilder); } output.Content.AppendLine(); output.TagName = ""; var sb = new StringBuilder(); AppendLocalizationScript(sb); var initializeFunctionName = "initializeFunction"; sb.AppendLine("<script type=\"text/javascript\">"); if (SelectedValueProperty != null) { if (OptionDataSet != null) { AppendInitializeSelectDataSetFunction(sb, OptionDataSet, initializeFunctionName, className); } else if (selectDropdownContext.OptionDataSet != null) { AppendInitializeSelectDataSetFunction(sb, selectDropdownContext.OptionDataSet, initializeFunctionName, className); } } else if (SelectedIdProperty != null) { AppendInitializeSelectAjaxFunction(sb, initializeFunctionName, className); } else { throw new NotImplementedException(); } sb.AppendLine(initializeFunctionName + "();"); sb.AppendLine("</script>"); output.Content.AppendHtml(sb.ToString()); }
public TagBuilder GenerateSelect(ViewContext viewContext, ModelExplorer modelExplorer, string optionLabel, string expression, IEnumerable <SelectListItem> selectList, bool allowMultiple, object htmlAttributes) { selectList = GetSelectListItems(viewContext, modelExplorer, expression, selectList, null); return(_htmlGenerator.GenerateSelect(viewContext, modelExplorer, optionLabel, expression, selectList, allowMultiple, htmlAttributes)); }
public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { output.TagName = string.Empty; output.TagMode = TagMode.SelfClosing; using (var sw = new StringWriter()) { var wrapper = new StringWriter(); var labelBuilder = new TagBuilder("label"); var selectBuilder = new TagBuilder("select"); var validationBuilder = new TagBuilder("validation"); var format = context.AllAttributes["asp-format"] != null ? context.AllAttributes["asp-format"].Value.ToString() : ""; var labelCss = context.AllAttributes["has-label"] != null ? context.AllAttributes["label-css"].Value.ToString() : ""; var inputCss = context.AllAttributes["input-css"] != null ? context.AllAttributes["input-css"].Value.ToString() : ""; var validationCss = Expression.Metadata.IsRequired || (context.AllAttributes["is-required"] != null && bool.Parse(context.AllAttributes["is-required"].Value.ToString())) ? context.AllAttributes["required-css"].Value.ToString() : ""; if (Expression.Metadata.IsRequired) { inputCss += " requiredField"; } // generate label if exist if (context.AllAttributes["has-label"] != null && bool.Parse(context.AllAttributes["has-label"].Value.ToString())) { labelBuilder = _generator.GenerateLabel(ViewContext, Expression.ModelExplorer, Expression.Name, Expression.Metadata.GetDisplayName(), new { @class = LabelCss }); labelBuilder.WriteTo(sw, NullHtmlEncoder.Default); } // generate actual input selectBuilder = _generator.GenerateSelect(ViewContext, Expression.ModelExplorer, "Please select", Expression.Name, SelectList, false, new { @class = inputCss, PlaceHolder = Expression.Metadata.GetDisplayName() }); foreach (var attribute in context.AllAttributes) { if (HtmlTagHelpers.IsAttributeAddible(attribute.Name)) { if (attribute.Name == "v-model-name") { selectBuilder.Attributes.Remove("v-model"); selectBuilder.Attributes.Add("v-model", attribute.Value.ToString()); } else if (attribute.Name == "v-get-text") { selectBuilder.Attributes.Remove("data-gettext"); selectBuilder.Attributes.Add("data-gettext", attribute.Value.ToString()); } else { selectBuilder.Attributes.Add(attribute.Name, attribute.Value.ToString()); } } } selectBuilder.WriteTo(sw, NullHtmlEncoder.Default); // generate validation if exist if (Expression.Metadata.IsRequired || (context.AllAttributes["is-required"] != null && bool.Parse(context.AllAttributes["is-required"].Value.ToString()))) { validationBuilder = _generator.GenerateValidationMessage(ViewContext, Expression.ModelExplorer, Expression.Name, null, ViewContext.ValidationMessageElement, new { @class = validationCss }); validationBuilder.WriteTo(sw, NullHtmlEncoder.Default); } // generate wrapper parent element if exist if (context.AllAttributes["has-parent"] != null && bool.Parse(context.AllAttributes["has-parent"].Value.ToString())) { wrapper.Write("<div class='" + context.AllAttributes["parent-css"].Value + "'>"); wrapper.Write(sw.ToString()); wrapper.Write("</div>"); } output.Content.SetHtmlContent(wrapper.ToString()); //output.PreContent.SetHtmlContent("<div class=''>"); //output.PostContent.SetHtmlContent("</div>"); return(base.ProcessAsync(context, output)); } }
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("&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>"); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { var placeholder = output.HasAttribute("placeholder") ? output.GetAttribute("placeholder") : ""; output.AddClass("form-group pmd-textfield"); var labelAttributes = new Dictionary <string, object>(); var selectAttributes = new Dictionary <string, object> { { "class", "select-simple form-control pmd-select2" } }; if (IsLg) { output.AddClass("form-group-lg"); } if (IsSm) { output.AddClass("form-group-sm"); } if (IsFloating) { output.AddClass("pmd-textfield-floating-label"); } if (HasWarning) { output.AddClass("has-warning"); } if (HasSuccess) { output.AddClass("has-success"); } if (HasError) { output.AddClass("has-error"); } if (Disabled) { selectAttributes.Add("disabled", "disabled"); } if (ReadOnly) { selectAttributes.Add("readonly", "readonly"); } if (Required) { selectAttributes.Add("required", "required"); } var inputPre = ""; var inputPost = ""; var labelClass = "control-label"; if (Icon != null) { inputPre = $"{inputPre}<div class=\"input-group\"><div class=\"input-group-addon\"><i class=\"material-icons md-dark pmd-sm\">{Icon}</i></div>"; inputPost = $"{inputPost}</div>"; labelClass = $"{labelClass} pmd-input-group-label"; } labelAttributes.Add("class", labelClass); var metadata = For.Metadata; var modelExplorer = For.ModelExplorer; var modelType = For.ModelExplorer.ModelType; if (Nullable.GetUnderlyingType(For.ModelExplorer.ModelType) != null) { modelType = Nullable.GetUnderlyingType(For.ModelExplorer.ModelType); } if (modelType.IsEnum) { var selectListItems = new List <SelectListItem>(); var enumNames = Enum.GetNames(modelType); var enumValues = Enum.GetValues(modelType); var attributes = modelType.GetCustomAttribute <DisplayAttribute>(); int i = 0; foreach (var name in enumNames) { var display = modelType.GetMember(name).First().GetCustomAttribute <DisplayAttribute>(); selectListItems.Add(new SelectListItem() { Text = display == null ? name : display.Name, Value = enumValues.GetValue(i).ToString() }); i++; } Items = selectListItems; } var select = _generator.GenerateSelect(ViewContext, modelExplorer, placeholder, For.Name, Items, Multiple, selectAttributes); var label = _generator.GenerateLabel(ViewContext, modelExplorer, For.Name, metadata.DisplayName, labelAttributes); var hidden = _generator.GenerateHidden(ViewContext, modelExplorer, For.Name, null, true, null); output.TagName = "div"; output.TagMode = TagMode.StartTagAndEndTag; string selectOutput; using (var writer = new StringWriter()) { label.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default); writer.Write(inputPre); select.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default); writer.Write(inputPost); hidden.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default); selectOutput = writer.ToString(); } output.Content.SetHtmlContent(selectOutput); }