Skip to content

Instantly share code, notes, and snippets.

@sniffdk
Last active September 28, 2017 18:09
Show Gist options
  • Save sniffdk/17779732567526da08e422104fd5b987 to your computer and use it in GitHub Desktop.
Save sniffdk/17779732567526da08e422104fd5b987 to your computer and use it in GitHub Desktop.
TagHelpers and ViewComponents poc
The basic idea is, that I want to avoid writing html in the tag helper class.
This poc, if it worked, would simply pass the ModelExpression down to a view component, where the actual html lives.
From there we would then render various tag helpers based on the ModelExpression.
Unfortunately, it seems that tag helpers in the view component simply creates a ModelExpression of the passed in ModelExpression, inception?
So, to make it work, I guess I would need to "trick" tag helpers into accepting an existing ModelExpression? Doable?
@model SomeModel
<div>
<form-group asp-for="SomeProperty" />
</div>
[HtmlTargetElement("form-group", TagStructure = TagStructure.WithoutEndTag)]
public class FormGroupTag : TagHelper
{
private const string ForAttributeName = "asp-for";
private readonly IViewComponentHelper _viewComponentHelper;
public FormGroupTag(IViewComponentHelper viewComponentHelper)
{
_viewComponentHelper = viewComponentHelper;
}
[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }
[HtmlAttributeName(ForAttributeName)]
public ModelExpression For { get; set; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = null;
((IViewContextAware)_viewComponentHelper).Contextualize(ViewContext);
var model = new FormGroupContext { For = For };
var result = await _viewComponentHelper.InvokeAsync("FromGroupComponent", model);
output.Content.SetHtmlContent(result);
}
}
public class FromGroupComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(FormGroupContext model)
{
return View(model);
}
}
@model FormGroupContext
<div class="form-group">
@*
Expectation:
<label for="SomeProperty" class="label">SomeProperty</label>
Actual result:
<label for="For" class="label">For</label>
*@
<label asp-for="For" class="label"></label>
<input type="text" asp-for="For" class="input" />
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment