How to fill an array in javascript using data sent through a list of models

I have a list in my model, EmployeeList

In my view, I want to populate an array from EmployeeList (from the model) and use it as tag autocomplete. It seems that the array is not populated with a list and autocomplete does not work. Help me please.

The code in the view is as follows:

<title>jQuery Autocomplete example</title> <script type="text/javascript" src="../../scripts/jquery-1.2.6.js"></script> <script type="text/javascript" src="../../scripts/jquery.autocomplete.js"></script> <!-- Listing 14.3 --> <script type="text/javascript"> $(document).ready(function() { var employeeList = '@Model.EmployeeLis.toArray();' $("#tags").autocomplete({ source: employeeList }); }); </script> 

  <h1>Type your name here</h1> <%= Html.TextBox("tags") %> 

+6
jquery asp.net-mvc-3 razor
source share
1 answer

You can use the JavaScriptSerializer class, which will generate a JSON representation of your model array:

 @using System.Web.Script.Serialization <title>jQuery Autocomplete example</title> <script type="text/javascript" src="@Url.Content("~/scripts/jquery-1.2.6.js")"></script> <script type="text/javascript" src="@Url.Content("~/scripts/jquery.autocomplete.js")"></script> <!-- Listing 14.3 --> <script type="text/javascript"> $(function() { var employeeList = @Html.Raw(new JavaScriptSerializer().Serialize(Model.EmployeeList)); $('#tags').autocomplete({ source: employeeList }); }); </script> 

Also notice how I used the helper Url.Content in the script inclusions to avoid hard-coding urls that might not work when deploying your application.

+15
source share

All Articles