Please help me to add default tag ('asp-for') in custom tag helper for checkboxlist. I want to use the tag like default.
Tag helper:
[HtmlTargetElement(Attributes = "asp-checklistbox, asp-modelname")]
public class CheckListBoxTagHelper : TagHelper
{
[HtmlAttributeName("asp-checklistbox")]
public IEnumerable<SelectListItem> Items { get; set; }
[HtmlAttributeName("asp-modelname")]
public string ModelName { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var i = 0;
foreach (var item in Items)
{
var selected = item.Selected ? @"checked=""checked""" : "";
var disabled = item.Disabled ? @"disabled=""disabled""" : "";
var html = $@"<label><input type=""checkbox"" {selected} {disabled} id=""{ModelName}_{i}__Selected"" name=""{ModelName}[{i}].Selected"" value=""true"" /> {item.Text}</label>";
html += $@"<input type=""hidden"" id=""{ModelName}_{i}__Value"" name=""{ModelName}[{i}].Value"" value=""{item.Value}"">";
html += $@"<input type=""hidden"" id=""{ModelName}_{i}__Text"" name=""{ModelName}[{i}].Text"" value=""{item.Text}"">";
output.Content.AppendHtml(html);
i++;
}
output.Attributes.SetAttribute("class", "th-chklstbx");
}
}
View:
<div asp-checklistbox="workTypeList" asp-modelname="workTypeId" asp-for="workTypeId"></div>
You can mimic asp-for
implementation from standard helpers.
Mark your tag helper with [HtmlTargetElement("mychecklistbox", Attributes = "asp-for")] and add to your CheckListBoxTagHelper
class this property:
/// <summary>
/// An expression to be evaluated against the current model.
/// </summary>
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }
And use this For
property for output HTML
you need to access the Model
detail like Name
. See standard helpers which use it - e.g. LabelTagHelper
or others.