I want to be able to dynamically (on page load) decide to set it to Visible=false
so it won't be rendered. I tried runat=server
but that's only for virtual paths.
One of the things that annoys me tremendously about HTML is that you can't write a self-closing script tag. E.g. is invalid. The <script> element is not allowed to be empty because it may contain inline code, and HTML is not smart enough to turn that feature on or off based on the presence of an attribute.
The reason for this is that HTML loads from top to bottom. The head loads first, then the body, and then everything inside the body.
JavaScript files have file extension . js . To use an external script put the name of the script file in the src attribute of a script tag. External scripts cannot contain script tags.
You can use ClientScriptManager.RegisterClientScriptBlock or ClientScriptManager.RegisterStartupScript to conditionally add the script.
if (condition)
{
String csname2 = "ButtonClickScript";
Type cstype = this.GetType();
StringBuilder cstext2 = new StringBuilder();
cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
cstext2.Append("Form1.Message.value='Text from client script.'} </");
cstext2.Append("script>");
cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
}
If you have script that is not small then you can put the script in some js file and use ClientScriptManager.RegisterClientScriptInclude
if (condition)
{
ClientScriptManager cs = Page.ClientScript;
cs.RegisterClientScriptInclude("ScriptKey", "ScriptURLToInclude");
}
In the ASP.NET markup language you can steer the rendering of any arbitrary contents. That is rendering a script tag only under certain conditions should be as simple as:
<% if (shouldRenderScriptTag) { %>
<script src="..." />
<% } %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With