Unable to write to a script tag in asp.net
-
16-06-2021 - |
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?
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";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow