I am creating a tag helper for a composite, custom dropdown list:
[HtmlTargetElement("mwrdropdown")] public class MwrDropDownTagHelper : TagHelper { public string AspFor { get; set; } public List<SelectListItem> SelectList { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { output.TagName = "div"; output.Attributes["class"] = "mwr-drop-down"; TagBuilder textArea = new TagBuilder("div"); textArea.Attributes["class"] = "mwr-drop-down-text"; TagBuilder textSpan = new TagBuilder("span"); textSpan.InnerHtml.Append(SelectList[0].Text); textSpan.AddCssClass("mwr-drop-down-text-span"); TagBuilder arrow = new TagBuilder("i"); arrow.AddCssClass("fa fa-chevron-circle-down mwr-drop-arrow"); TagBuilder dropPanel = new TagBuilder("div"); dropPanel.AddCssClass("mwr-drop-panel"); int counter = 0; foreach(var item in SelectList) { TagBuilder selectItem = new TagBuilder("div"); selectItem.MergeAttribute("data-select-value", item.Value); selectItem.AddCssClass("mwr-select-item"); if (counter == 0) { selectItem.AddCssClass("selected"); } selectItem.InnerHtml.Append(item.Text); dropPanel.InnerHtml.Append(selectItem);++counter; } TagBuilder hidden = new TagBuilder("input"); hidden.MergeAttribute("type", "hidden"); hidden.MergeAttribute("asp-for", AspFor); textArea.InnerHtml.Append(textSpan); textArea.InnerHtml.Append(arrow); output.Content.Append(textArea); output.Content.Append(dropPanel); output.Content.Append(hidden); }//Process() }//class MwrDropDownTagHelper
My View Model class has a Required Annotation for the Category Property
and this is my markup:
<mwrdropdown asp-for="Category" select-list="@Model.Categories"></mwrdropdown>
Here is the generated html:
<div class="mwr-drop-down"><div class="mwr-drop-down-text"><span class="mwr-drop-down-text-span">select a category</span><i class="fa fa-chevron-circle-down mwr-drop-arrow"></i></div><div class="mwr-drop-panel"><div class="selected mwr-select-item" data-select-value="">select a category</div><div class="mwr-select-item" data-select-value="tutorial">tutorial</div><div class="mwr-select-item" data-select-value="article">article</div></div><input asp-for="Category" type="hidden"></div>
I was hoping that I could just "pass through" the - asp-for - attribute and the framework would generate the validation attributes. I am guessing these are generating before my "trans-piled" html hits the DOM. Is there anyway to do this without having to manually populate the validation attributes?
Thanks in advance!