0

i have an asp.net mvc4 application razor, in which i'd like to add the auto-complétion features, i added a sample table availableTags with différents values and it works, but when i try an ArrayList to a javascript table:

@{
    ArrayList elements = new ArrayList();
    elements=(ArrayList)Session["elements"];

}
     <script>
            $(function () {
                var champ = "@elements";
                var availableTags = [
                  "ActionScript",
                  "AppleScript",
                  "Asp",
                  "BASIC",
                  "C",
                  "C++",
                  "Clojure",
                  "COBOL",
                  "ColdFusion",
                  "Erlang",
                  "Fortran",
                  "Groovy",
                  "Haskell",
                  "Java",
                  "JavaScript",
                  "Lisp",
                  "Perl",
                  "PHP",
                  "Python",
                  "Ruby",
                  "Scala",
                  "Scheme"
                ];
              $("#tags").autocomplete({
                    source: champ
                });
            });
      </script> 

it fails!!! What the reason of this problem? How can i fix it?

1 Answer 1

2

You can't just set javascript variables to C# variables. Razor processes your CSHTML and outputs html. The javascript executes on the client. What does your produced HTML look like? I think you need to convert it to JSON, try something like this:

@{
    ArrayList elements = new ArrayList();
    elements=(ArrayList)Session["elements"];
    var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
    var json = ser.Serialize(elements);
    var html = new HtmlString(json);
}
<script>
    $(function () {
        var champ = @html;
Sign up to request clarification or add additional context in comments.

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.