Question

I have a script that I want only to load if a certain condition was met, so I figured I should do this:

//Head tag
<script type="text/javascript" id="scriptArea" runat="server"></script>
//Rest of the page

.cs (Page_Load event)

if(someCondition)
{
    scriptArea.InnerHtml = "Javascript code";
}

The problem is I get a null pointer exception and when it stops, I discover that scriptArea is null for some reason. Why does this happen and do you know of another solution?

Était-ce utile?

La solution

Using asp.net webforms and script runat="server" ends up being server executed code, see MSDN on documentation about this.

If you just want javascript, try this instead:

<script type="text/javascript">
    <asp:literal id="scriptArea" runat="server" />
</script>

Then in your code behind

scriptArea.Text = "Javascript code";
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top