Skip to content

Instantly share code, notes, and snippets.

@RichardD2
Last active June 27, 2018 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RichardD2/031157903e6bdc881ccc51df5d95a39f to your computer and use it in GitHub Desktop.
Save RichardD2/031157903e6bdc881ccc51df5d95a39f to your computer and use it in GitHub Desktop.
ASP.NET Core TagHelper to load element attributes from ViewData.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace AspNetCore.Helpers
{
[HtmlTargetElement(Attributes = ViewBagKeyAttributeName)]
public class HtmlElementAttributeTagHelper : TagHelper
{
private const string ViewBagKeyAttributeName = "asp-attributes-key";
[ViewContext]
[HtmlAttributeNotBound]
public ViewContext ViewContext { get; set; }
[HtmlAttributeName(ViewBagKeyAttributeName)]
public string AttributesKey { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (!string.IsNullOrWhiteSpace(AttributesKey))
{
var attributes = ViewContext.ViewData[AttributesKey];
switch (attributes)
{
case IDictionary<string, object> dict:
{
foreach (var attr in dict)
{
output.Attributes.Add(attr.Key, attr.Value);
}
break;
}
case object obj:
{
foreach (var attr in HtmlHelper.AnonymousObjectToHtmlAttributes(obj))
{
output.Attributes.Add(attr.Key, attr.Value);
}
break;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment