diff --git a/Sakura.AspNetCore.Extensions/Sakura.AspNetCore.Mvc.TagHelpers/FlagsEnumInputTagHelper.cs b/Sakura.AspNetCore.Extensions/Sakura.AspNetCore.Mvc.TagHelpers/FlagsEnumInputTagHelper.cs index aa310a8..823afd0 100644 --- a/Sakura.AspNetCore.Extensions/Sakura.AspNetCore.Mvc.TagHelpers/FlagsEnumInputTagHelper.cs +++ b/Sakura.AspNetCore.Extensions/Sakura.AspNetCore.Mvc.TagHelpers/FlagsEnumInputTagHelper.cs @@ -1,5 +1,6 @@ using System; using JetBrains.Annotations; +using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.TagHelpers; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Razor.TagHelpers; @@ -26,9 +27,10 @@ public class FlagsEnumInputTagHelper : TagHelper /// Creates a new . /// [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] - public FlagsEnumInputTagHelper(IHtmlGenerator htmlGenerator) + public FlagsEnumInputTagHelper(IHtmlGenerator htmlGenerator, IHtmlHelper htmlHelper) { HtmlGenerator = htmlGenerator; + HtmlHelper = htmlHelper; } /// @@ -43,6 +45,18 @@ public FlagsEnumInputTagHelper(IHtmlGenerator htmlGenerator) [PublicAPI] protected IHtmlGenerator HtmlGenerator { get; } + /// + /// The Service object. + /// + [PublicAPI] + protected IHtmlHelper HtmlHelper { get; } + + /// + /// The Service object. + /// + [ViewContext] + public ViewContext ViewContext { get; set; } + /// /// Get or set the model expression to retrieve the enum flag value from model. /// @@ -74,7 +88,6 @@ public override void Process(TagHelperContext context, TagHelperOutput output) throw new InvalidOperationException( $"The model expression type must be enum flag when {EnumFlagValueAttributeName} is specified"); - // Get base type and remove nullable var type = EnumFlagFor.ModelExplorer.ModelType; type = Nullable.GetUnderlyingType(type) ?? type; @@ -85,8 +98,28 @@ public override void Process(TagHelperContext context, TagHelperOutput output) throw new InvalidOperationException( $"The value of the {EnumFlagValueAttributeName} attribute is not a valid enum flag item."); + var name = ""; + if (ViewContext != null) + { + ((IViewContextAware)HtmlHelper).Contextualize(ViewContext); + + // Now you can use the HtmlFieldPrefix if set + name = ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix; + if (!string.IsNullOrEmpty(name)) + { + name += "."; + } + } + + name += EnumFlagFor.Name; + + // Set id if possible + if (ViewContext != null) + { + output.Attributes.SetAttribute("id", HtmlHelper.GenerateIdFromName($"{name}.{enumName}")); + } // Set name and value - output.Attributes.SetAttribute("name", EnumFlagFor.Name); + output.Attributes.SetAttribute("name", name); output.Attributes.SetAttribute("value", enumName); // Set checked attribute