Sep 14, 2018

ASP.NET Core 2.1 - custom tag helper - render all hidden fields from model marked with Hidden attribute


Creating custom tag helper to inspect provided model
 public class StudentExamViewModel : ExamBaseViewModel
    {
        [HiddenInput]
        public int StudentId { get; set; }       
    }

 [HtmlTargetElement("hidden-fields")]
    public class HiddenFieldsTagHelper : TagHelper
    {
        [HtmlAttributeName("for-model")]
        public ModelExpression Model { get; set; }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "div";
            output.TagMode = TagMode.StartTagAndEndTag;
            var sb = new StringBuilder();         
            Model.ModelExplorer.ModelType.GetProperties()
                                 .Where(prop => Attribute.IsDefined(prop, typeof(HiddenInputAttribute)))
                                 .ToList()
                                 .ForEach(hp =>
                                 {
                                    var propVal = Model.Model.GetType().GetProperty(hp.Name).GetValue(Model.Model, null);
                                    sb.AppendFormat($"<input type='hidden' name='{hp.Name}' value='{propVal}' />");
                                 });
            output.PreContent.SetHtmlContent(sb.ToString());
        }
    }

Use in View:

 <hidden-fields for-model="@Model" />

Register in ViewImports.cshtml:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Web
Note that you need to reference root namespace!

No comments:

Post a Comment