Julius A
Julius A

Reputation: 39622

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

Upvotes: 6

Views: 8585

Answers (5)

fonsIT
fonsIT

Reputation: 61

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.

Upvotes: 3

Joel Coehoorn
Joel Coehoorn

Reputation: 415800

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.

Upvotes: 4

Anders Rune Jensen
Anders Rune Jensen

Reputation: 3796

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/

Upvotes: 0

Maxam
Maxam

Reputation: 4051

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

Upvotes: 3

StingyJack
StingyJack

Reputation: 19469

Convert it to string representation of a javascript array ("['val1','val2','val3']") and shove it into the value field of a hidden input.

Upvotes: 3

Related Questions