Question

I have an application which will hold a number of datasets. I want to create a text box with autocomplete matching the dataset title. Initially I used jQuery's autocomplete widget searching the database and that worked. However, it was too slow and database intensive.

I am now trying to implement it by grabbing the list of titles when I build the model and using that for the autocomplete. However I can't get it working.

In my model I have

public IEnumerable<string> DatasetTitles { get; set; }

and in the view

@Html.EditorFor(m => m.SearchFreeText)

and

    $(document).ready(function() {
    $('#SearchFreeText').autocomplete({
        source: '@Model.DatasetTitles.ToArray()'
    });
});

This fails with a 404 error as it tries to fetch data from the location 'System.String[]'. This is probably because the widget expects a URL when given a string.

Next I tried removing the single quotes so it would treat it as an array rather than a string.

source: @Model.DatasetTitles.ToArray()

but this gives a syntax error.

Is there a way to get an autocomplete list of terms from the model?

Was it helpful?

Solution

You need to convert your C# array into a valid javascript Array (i.e. ["a","b","c"...]). There are many ways to do that here is my suggestion:

string.Concat("[", string.Join(",", Model.DatasetTitles.Select(s => string.Concat("'", s, "'"))), "]");

In essence I am taking each element in the DatasetTitles collection and transforming it to a javascript string literal. Then joining those all up with , separators and finally putting square brackets around the whole thing.

Not particularly elegant and there are almost certainly better ways to transform the data but hopefully that will get you on the right track.

EDIT: You could also look at the JavaScriptSerializer which is the frameworks class for converting C# objects to valid javascript. This is probably perferrable over manually transforming the data as shown above. See this answer for an example: https://stackoverflow.com/a/9024029/61470

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top