Create javaScript variable in code behind of asp.net

How do I register a Javascript variable on the server side (backend) and access it on the client side (Javascript file), without a hidden field, Literal, etc.?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use the RegisterClientScriptBlock-Function from the Page’s ClientScriptManager.

Page.ClientScript.RegisterClientScriptBlock(Page.GetType, "initMyClientVariable", "var myClientVariable=null;", True)

EDIT: according to your new informations, that you want to register a client array, use ClientScriptManager’s RegisterArrayDeclaration Method.

VB.Net example:

Dim myArrayValue As String = """1"", ""2"", ""text"""
Page.ClientScript.RegisterArrayDeclaration("myClientArray", myArrayValue)

According to the new information in my comments that you need access to that variable from an external js-file: you should pass the js-array as argument to the function in the js-file. For example:

callFunctionInJsFile(checkBoxes);

Method 2

You can put the following code in .aspx file …

<script type="text/javascript" >
    var date1 = "<%: DateTime.Now %>";
    var date2 = "<%= DateTime.Now %>";
</script>

<%:  %> works under ASP.NET 4

Method 3

You can put a literal in the xml portion of the code and assign that literal some text:

myLiteral.Text = "<script language="javascript">var myVar = 24;</script>";

This makes myVar globally available on the client side once it’s rendered. You can also use the ClientScriptManager object to use Asp.Net to inject scripts and variables.

Method 4

First place an <asp:Literal ID=”Literal1″ runat=”server”></asp:Literal> tag in the <head> of your .aspx file.

Then in the server side code in your .aspx.cs file, do something like Literal1.Text = “<script type=”text/javascript”>var timer = 3600</script>” and you’ve got yout javascript variable called timer.

That’s it. Have fun!


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x