0

In my controller's action method, I am storing data in view data like the below:

int[] numbers =  new  int[] {10, 20, 30, 40};
ViewData["Numbers"] =numbers;

now in my view, from jQuery trying to get data into array. I've tried like below:

<script type="text/javascript">
   var tempArray = ['@ViewData["Numbers"]'];  
</script>

but when I loop throw the tempArray, it is printing values like below:

Index  Value 
0      int[]

for value instead of printing 10, printing some array. My question is How to retrieve array from view data in jQuery?

Thanks in advance

2
  • Have you tried @ViewData["Numbers"] without the single quotes and []? That could give you want you're looking for as when the rendering engine processes it, it would put the contents of that string into the right side of that setter. It looks like because it's surrounded by the [] it's putting your array into the first position of an outside array. Commented Mar 1, 2013 at 3:33
  • At first, I've tried with out putting [] around Viewdata["Numbers]" in script code, that gave me same result. Commented Mar 1, 2013 at 4:13

1 Answer 1

2

store that array as a string:

string numbers =  "10, 20, 30, 40";
ViewData["Numbers"] = numbers;

or convert that array into a string:

int[] numbers =  new int[] {10, 20, 30, 40};
ViewData["Numbers"] = numbers.toString();

JS:

var tempArray = [@ViewData["Numbers"]];

Now tempArray is an array containing the four integers.

Sign up to request clarification or add additional context in comments.

2 Comments

Should be [@ViewData["Numbers"]] ?
That's what I did, I thought there may be a better way than converting numbers array into string. so posted that question here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.