Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send assign a List<string> to a JavaScript array or enumerable object

I have the following :

ViewBag.SomeEnumerable = new List<string>() { "string1", "string2" };

Now how do I assign ViewBag.SomeEnumerable to an array or some form of enumerable object on the JavaScript side? e.g.:

function SomeFunction()
{
  var array = @ViewBag.SomeEnumerable;
  for(var eachItem in array)
  {
    alert(eachItem); // should display "string1" then string2"
  }
}
like image 565
Eminem Avatar asked Sep 12 '12 09:09

Eminem


People also ask

How do you turn a string into an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

What is the correct way to write a JavaScript array object?

Creating an Array Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.

Can you use lists in JavaScript?

In JavaScript, as in most languages, we have a data structure that deals with lists of values. It's a very handy object that lets us group values together in an ordered list.


1 Answers

<script type="text/javascript">
function SomeFunction() {
    var array = @Html.Raw(Json.Encode(ViewBag.SomeEnumerable));
    for(var i = 0; i < array.length; i++) {
        alert(array[i]); // should display "string1" then string2"
    }
}
</script>

will be rendered as:

<script type="text/javascript">
function SomeFunction() {
    var array = ["string1","string2"];
    for(var i = 0; i < array.length; i++) {
        alert(array[i]); // should display "string1" then string2"
    }
}
</script>
like image 90
Darin Dimitrov Avatar answered Sep 28 '22 01:09

Darin Dimitrov