2

I have a List<string> in my Model C# filled on runtime, called @Model.Names in my Views.

After filling that list I want to fill an array in javascript from values of that list, in order to do the following:

 var myArray = [];

//fill myArray with values from @Model.Names

 $("#tags").autocomplete({
   source: myArray 
  });

So when the user types in <input id="tags"> he will get an autocomplete with a list of the names I filled on runtime.

Any idea how to do so?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
HelpASisterOut
  • 3,085
  • 16
  • 45
  • 89
  • 2
    Check out this post: http://stackoverflow.com/questions/18470702/how-do-i-convert-a-c-sharp-liststring-to-a-javascript-array – andreasnico Nov 15 '16 at 16:16

2 Answers2

3

I prefer this way. No manual Looping, and you can do this with fairly complex viewmodels as well (as long as there are no recursive references within your types).

var myArray = @Html.Raw(Json.Encode(Model.Names))

$("#tags").autocomplete({
    source: myArray 
});
Dylan Hayes
  • 2,331
  • 1
  • 23
  • 33
2

you can try the following.

<script type="text/javascript">
    var myArray = [];
    @foreach (var name in Model.Names)
    {
        @:myArray.push("@name");
    }
</script>
mausinc
  • 527
  • 4
  • 14