How to programmatically create a <script> tag and script on an ASP.NET page?

From time to time I come across a situation in which I could solve this problem by dynamically creating a piece of JavaScript, spesific for this page instance, which I could then insert into the final markup. This is usually due to the fact that I want some kind of behavior to occur on the client side, and not on the server side, and creating static JavaScript is not an option.
For example, when trying to send the source file path without sending the file itself , when trying to do this for several dynamically created components.

How would you recommend me to create a tag scriptand populate it, for example, JavaScript?

+3
source share
1 answer

Use your page ClientScriptManagerand RegisterClientScriptBlock().

string javascript = "javascript goes here"; 
string scriptname = "Name of this script"; // used to prevent adding the same script twice at two places in the page life cycle
if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptname)) 
{ 
    Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), scriptname, javascript, true); 
} 
+8
source

Source: https://habr.com/ru/post/1705259/


All Articles