using System; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Mvc.Rendering; namespace AMWD.Common.AspNetCore.Extensions { /// /// Extensions for the HTML (e.g. ). /// public static class HtmlExtensions { /// /// The prefix used to identify JavaScript parts. /// public static string JSPrefix { get; set; } = "_JS_"; /// /// The prefix used to identify CascadingStyleSheet parts. /// public static string CSSPrefix { get; set; } = "_CSS_"; /// /// Add a js snippet. /// /// The dynamic type of the . /// The instance. /// The template to use to add the snippet. /// public static T AddJS(this IHtmlHelper htmlHelper, Func template) { htmlHelper.ViewContext.HttpContext.Items[$"{JSPrefix}{Guid.NewGuid()}"] = template; return default; } /// /// Renders the js snippets into the view. /// /// The dynamic type of the . /// The instance. /// public static T RenderJS(this IHtmlHelper htmlHelper) { foreach (object key in htmlHelper.ViewContext.HttpContext.Items.Keys) { if (key.ToString().StartsWith(JSPrefix) && htmlHelper.ViewContext.HttpContext.Items[key] is Func template) htmlHelper.ViewContext.Writer.WriteLine(template(null)); } return default; } /// /// Add a css snippet. /// /// The dynamic type of the . /// The instance. /// The template to use to add the snippet. /// public static T AddCSS(this IHtmlHelper htmlHelper, Func template) { htmlHelper.ViewContext.HttpContext.Items[$"{CSSPrefix}{Guid.NewGuid()}"] = template; return default; } /// /// Renders the css snippets into the view. /// /// The dynamic type of the . /// The instance. /// public static T RenderCSS(this IHtmlHelper htmlHelper) { foreach (object key in htmlHelper.ViewContext.HttpContext.Items.Keys) { if (key.ToString().StartsWith(CSSPrefix) && htmlHelper.ViewContext.HttpContext.Items[key] is Func template) htmlHelper.ViewContext.Writer.WriteLine(template(null)); } return default; } } }