3

Hello i have this code in the controller :

   ViewBag.localitate = db.Localitatis.OrderBy(p => p.Localitate).ToList();

and on the view i try to get it via:

<script type="text/javascript">
    $(function () {
        var availableTags = [
         @foreach (var item in ViewBag.localitate)
              {
                       @item.Localitate 
             }


    ];
        $("#destination").autocomplete({
            source: availableTags
        });
    });
</script>

I din't know how to format this in order to get an array like in the jquery demo example :

"ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"

in order to make the autocomplete work with my values from database,

thank you

2 Answers 2

2
<script type="text/javascript">
    $(function () {
        $("#destination").autocomplete({
            source: @Html.Raw(Json.Encode(ViewBag.localitate))
        });
    });
</script>

If you have lots of data, consider using a server-side controller action to perform the filtering.

Sign up to request clarification or add additional context in comments.

Comments

0

First, set your view data to only have the actual names you want:

ViewBag.localitate = db.Localitatis.Select(p => p.Localitate).OrderBy(p => p).ToList();

Then the simplest way to render this in javascript would be:

var availableTags = [" @String.Split("\,\"", ViewBag.localitate) "];

But I'd recommend using a JSON parser like JSON.NET instead. This way you don't have to worry about cross-site scripting attacks and such, since things are escaped for you.

var availableTags = @(JsonConvert.Serialize(ViewBag.localitate));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.