I need to pass values from my asp.net code to a javascript code block in the page.
I know at least two ways to do this:
<script runat=server>
int a = 42;
protected override void OnInit(EventArgs e)
{
lbl.Text = "42";
}
</script>
<script>
var a = <%= a %>;
var b = <asp:Literal runat=server id=lbl>/>;
alert("the meaning of life=" + a + " or " + b);
</script>
But is there a better way in asp.net WebForms to bind the value of a variable in asp.net code to a javascript block? Both of these seem messy because they don’t support intellisense.
I ended up doing something which I think it more robust. In master page I added this:
Then I append the result of this function to the page:
So now I can do this:
and in my final page, I get:
So now I have a robust way to pass values with types correctly managed to the page without script blocks or labels.