Monday, February 3, 2020

using Razor TagHelpers?

This will have you making something like this:

using System;
using System.IO;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Portal.Web.TagHelpers
{
   [HtmlTargetElement("angular-app")]
   public class AngularAppTagHelper : TagHelper
   {
      public AngularAppTagHelper()
      {
      
      }
      
      public string App { get; set; }
      
      public override void Process(TagHelperContext context, TagHelperOutput output)
      {
         //throw new Exception("yikes");
         using (var sr = new StreamReader(AppDomain.CurrentDomain.BaseDirectory +
               @"\ClientApp\dist" + App + @"\index.html"))
         {
            string htmlRaw = sr.ReadToEnd();
            
            var htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(htmlRaw);
            
            var body =
                  htmlDoc.DocumentNode.ChildNodes.FindFirst("body").ChildNodes.Where(x
                  => x.Name == "script");
            StringBuilder sb = new StringBuilder("");
            
            foreach (var item in body)
            {
               string scriptTag = String.Format("$<script src=\"/ClientApp/dist/{0}/{1}\">
                     </script>", App, item.Attributes["src"].Value);
               sb.AppendLine(scriptTag);
            }
            
            output.Content.AppendHtml(new HtmlString(sb.ToString()));
         }
      
      }
   }
}

 
 

In the name of injecting Angular 2+ gunk into Razor views like so:

<app-root></app-root>
@section Scripts{
   <angular-app app="portal"></angular-app>
}

 
 

\Views\_ViewImports.cshtml gets this in it:

@using Portal.Web.TagHelpers
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

 
 

I cannot for the life of me get any of this to work. I cannot set a breakpoint inside of the Process method and land in there. Lame!

No comments:

Post a Comment