How to pass array from Asp.net server side to Javascript function on client side

How do I pass an array I have created on the server side onto the client side for manipulation by Javascript?

Any pseudo code will help

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’ll need to embed it as a javascript array declaration into the page. There are a number of ways to do this, but it generally means turning the array into text that you write to the page, probably using the ClientScriptManager.

I’m hoping for better javascript integration in a upcoming verison of ASP.Net. Moving the value of a server variable —any server variable— to the client ought to be supported with a simple, one-line function call. Not the back-flips we need right now.

Method 2

Convert it to string representation of a javascript array (“[‘val1′,’val2′,’val3’]”) and shove it into the value field of a hidden input.

Method 3

Another way would be to use the RegisterArrayDeclaration method of the Page object (deprecated) or in the ClientScriptManager class. See MSDN for details.

Method 4

The way I do it is like this:

aspx:

    private string buttonarray =  "'but1','but2','but3','but4'";

    public string Buttonarray
    {
        get { return buttonarray; }
    }

javascript

var buttonarray = new Array(<%=Buttonarray%>);

I hope this helps.

Method 5

Easiest way is to convert it to json. Then just put it at the top of the page in a variable. I’ve found this the best json implementation for .net: http://litjson.sourceforge.net/


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