Last active
June 27, 2018 17:25
-
-
Save RichardD2/031157903e6bdc881ccc51df5d95a39f to your computer and use it in GitHub Desktop.
ASP.NET Core TagHelper to load element attributes from ViewData.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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