Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically not render a script tag?

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.

like image 977
ispiro Avatar asked May 23 '14 11:05

ispiro


People also ask

Can a script tag be self closing?

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.

Why do script tag appear in body instead of head?

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.

Can I put script tag outside 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.


2 Answers

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");
}
like image 163
Adil Avatar answered Oct 05 '22 11:10

Adil


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="..." />
<% } %>
like image 39
chiccodoro Avatar answered Oct 05 '22 13:10

chiccodoro