How to render scripts, generated in TagHelper process method, to the bottom of the page rather than next to the tag element?

后端 未结 7 1416
情深已故
情深已故 2020-12-11 06:28

I am generating scripts in process method of TagHelper class as follows

[TargetElement(\"MyTag\")]
    public Class MYClass: TagHelper{
      public override         


        
7条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 07:02

    I know this thread is old, but if someone is looking for an easy fix to run some javascript here is a way.

    First, ViewComponents render server side, so naturally, client side scripts wont be ready at this point. As others have pointed out you can render some section scripts where needed that will interpret your tag helper, this is great for decoupling, and you just include the script where needed.

    But often your tag helper takes data as input that is relevant for the client side script. To be able to run this data through a js function you could do something like this.

    TagHelper.cs

    var data= $@"
            '{Id}', 
            '{Title}', 
            {JsonConvert.SerializeObject(MyList)}";
    
    output.Attributes.SetAttribute("data-eval", data);
    

    site.js

    $(".tag-helper-class").each((i, e) => {
        const jq = $(e);
    
        const data= jq.data("eval");
    
        if (!data) {
            return;
        }
        jq.attr("data-eval", "");
        eval(`myJsFunction(${data})`);
    });
    

    Now when the scripts are ready they can look for your tag helper and execute the proper function with the relevant data.

提交回复
热议问题