Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate an array in javascript using data sent through Model List

I have a list in my model, EmployeeList

In my View I want to to populate an array from EmployeeList(from Model) and use it as autocomplete for tags. It seems that the array isn`t being poplulated from the List nor is the autocomplete working. Help 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") %>

like image 708
learning Avatar asked Mar 21 '11 09:03

learning


1 Answers

You could use the JavaScriptSerializer class which will generate a JSON representation of you 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 note the way I have used the Url.Content helper in the script inclusions to avoid hardcoding urls which might not work when your application is deployed.

like image 167
Darin Dimitrov Avatar answered Nov 06 '22 20:11

Darin Dimitrov