There are a few ways to insert html content or scripts from ASP.NET C# code behind:
1. a. Place a static html content or script in an html server control (eg. Div). To turn an html tag/element into an html server control, try the following methods:
Right-click on the control and select Run As Server Control or set the attributes "runat" of the control to "server". If both are not available or disabled (typical for an html element), add runat="server" to the control directly in the markup file:
Code:<div id="histatsVariable" runat="server">
Code:<div id="histatsCounter" runat="server">
Notes:
that runat="server", cannot enabled for div from the properties of the control) or turned into an HTML server control ().
b. Turn the html content or script on / off in Page_Load() based on a global flag. For example,
Code: if (!Utilities.bEnableHistats)
{
histatsVariable.InnerHtml = "";
histatsCounter.InnerHtml = "";
}
2. Place the static html content or script as a global string in a Utilities class. so that it can be disabled or commented out easily in all the files.
a. Define an html server control Div.
b. Load the script in Page_Load().
3. Place a static html content or script in an htm file. so that it can be disabled or commented out easily in all the files.
a. Define an html server control iframe pointing to the file within an html server control Div.
b. Load the script in Page_Load().
Related links:
1.
Using JavaScript Along with ASP.NETRegisterStartupScript MethodCode:Page.RegisterStartupScript("MyScript",
"<script language=javascript>" +
"function AlertHello() { alert('Hello ASP.NET'); }</script>");
RegisterClientScriptBlock MethodCode: void Page_Load(object sender, EventArgs e) {
Page.RegisterClientScriptBlock("MyScript",
"<script language=javascript>" +
"if (document.images) {" +
"MyButton = new Image;" +
"MyButtonShaded = new Image;" +
"MyButton.src = 'button1.jpg';" +
"MyButtonShaded.src = 'button2.jpg';" +
"}" +
"else {" +
"MyButton = '';" +
"MyButtonShaded = '';" +
"}" +
"</script>");
The Difference Between RegisterStartupScript and RegisterClientScriptBlockThe main difference is that the RegisterStartupScript method places the JavaScript at the bottom of the ASP.NET page right before the closing </form> element. The RegisterClientScriptBlock method places the JavaScript directly after the opening <form> element in the page.
Keeping JavaScript in a Separate File (.js)Code:Page.RegisterClientScriptBlock("MyScript",
"<script language=javascript src='MyJavaScriptFile.js'>");
Once the .js file is imported into the ASP.NET page, any of the JavaScript functions can be called as before. This is a great way to manage JavaScript functions and keep them separate from the other logic of ASP.NET pages. It is also an easy way to use the same JavaScript functions on multiple ASP.NET pages.
2.
How to dynamically load any html file component