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.TagHelpersNote that you need to reference root namespace!
@addTagHelper *, Web
No comments:
Post a Comment