10

I have a js code in which an array works well when its like

var availableTags = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            "C"
];

I then made an array string in my code behind or .cs like on class level

 public static string[] test={"animal","lovely"};

I then changed the JS array to this

var availableTags =  "<%=test%>"; // also tried without quotes 

Now I m not having the results as was having with previous js array

Editing with complete code, the jQuery I taken from http://jqueryui.com/demos/autocomplete/#multiple

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Collections;
using System.Web.Script.Serialization;

public partial class onecol : System.Web.UI.Page
{
   JavaScriptSerializer serializer;

   public static string test = "['animal','lovely']";
    public static string check;

   
    protected void Page_Load(object sender, EventArgs e)
    {
       serializer = new JavaScriptSerializer();
        //serializer
        this.detail.ToolsFile = "BasicTools.xml";
        test = returnTitle();
    }
   
}

and the script with html is

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript" src="Jscript.js"></script>  
     <script type="text/javascript" src="jquery-1.7.1.min.js"></script> 
     <script type="text/javascript" src="jquery-ui-1.8.17.custom.css"></script>  
     <link href="~/jquery-ui-1.8.17.custom.css" rel="stylesheet" type="text/css"/>
      <script type="text/javascript">
          $(function () {
                var availableTags =  <%=test%>;
             
              function split(val) {
                  return val.split(/,\s*/);
              }
              function extractLast(term) {
                  return split(term).pop();
              }

              $("#tags")
              // don't navigate away from the field on tab when selecting an item
            .bind("keydown", function (event) {
                if (event.keyCode === $.ui.keyCode.TAB &&
                        $(this).data("autocomplete").menu.active) {
                    event.preventDefault();
                }
            })
            .autocomplete({
                minLength: 0,
                source: function (request, response) {
                    // delegate back to autocomplete, but extract the last term
                    response($.ui.autocomplete.filter(
                        availableTags, extractLast(request.term)));
                },
                focus: function () {
                    // prevent value inserted on focus
                    return false;
                },
                select: function (event, ui) {
                    var terms = split(this.value);
                    // remove the current input
                    terms.pop();
                    // add the selected item
                    terms.push(ui.item.value);
                    // add placeholder to get the comma-and-space at the end
                    terms.push("");
                    this.value = terms.join(", ");
                    return false;
                }
            });
          });
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<div class="demo" >
<div class="ui-widget">
    <label for="tags">Tag programming languages: </label>
    <input id="Text1" class="#tags" size="50" />


</div>
</div>

actually its a auto complete functionality to give tags ,the auto complete suggestions for tagging I want to get from C# code ,I took Jquery source from jqueryui.com/demos/autocomplete/#multiple and then I tried to give it C# string from .cs file , I explained it with code on edited version , with C# code behind it works exactly as its in the link

1
  • @TimSchmelter edited ,please check Commented Jan 26, 2012 at 20:08

6 Answers 6

26

You need to serialize the C# string array into a javascript array.

http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

Usually I create a simple static class as a wrapper.

public static class JavaScript
{
    public static string Serialize(object o)
    {            
        JavaScriptSerializer js = new JavaScriptSerializer();
        return js.Serialize(o);
    }
}

Then you can use that class to serialize the item you need to

//C# Array(Member of asp page)
protected string[] Values = { "Sweet", "Awesome", "Cool" };

<script type="text/javascript">
    var testArray = <%=JavaScript.Serialize(this.Values) %>
</script>
0
7
var availableTags =  ['<%=String.join("','",test)%>'];
3
  • It should be noted that if any of your strings contain a single quote, these should be escaped. Commented Jan 26, 2012 at 19:37
  • Compiler Error Message: CS0117: 'String' does not contain a definition for 'join' Commented Jan 26, 2012 at 19:55
  • @user1074474 It was giving me the same error. Were you doing an online coding challenge? I think that some commands aren't allowed in some of those, unless I'm missing something. In order to do a workaround, I just created a StringBuilder and iterated over the array, adding integer values, then parsing a string from the result. Commented Sep 29, 2022 at 15:37
3

It would be something like this...

var availableTags =  ["<%= string.Join("\", \"", test) %>"];

or

var availableTags =  ['<%= string.Join("', '", test) %>'];

The first one would render as

var availableTags = ["Sweet", "Awesome", "Cool"];

and the second one would render as

var availableTags = ['Sweet', 'Awesome', 'Cool']; 

both of which are fine for autocomplete.

12
  • I tried it with/without quotes/[] and with ' ' as well , but still not working Commented Jan 26, 2012 at 19:42
  • @user1074474, What do you mean by "not working"? Show us the error or the rendered HTML (do view source). Commented Jan 26, 2012 at 19:51
  • @user1074474, We don't have to see the full source code. All we need to see is the error if you are getting or relevant portion of rendered HTML. Commented Jan 26, 2012 at 20:02
  • actually its a auto complete functionality to give tags ,the auto complete suggestions for tagging I want to get from C# code ,I took Jquery source from jqueryui.com/demos/autocomplete/#multiple and then I tried to give it C# string from .cs file , I explained it with code on edited version , with C# code behind it works exactly as its in the link Commented Jan 26, 2012 at 20:13
  • Do view source in your browser and search for var availableTags = <What Is Rendered Here?>; Commented Jan 26, 2012 at 20:17
1

test property should be a string property and it should render the string which will be parsed by Js engine as an array. Try this.

Code behind property

public static string test= "['animal','usman lovely']";

JS

 var availableTags =  <%=test%>;//No quotes
4
  • Should probably drop the curly braces and define it as string. Commented Jan 26, 2012 at 19:29
  • What do you see in the source when the page is rendered? Commented Jan 26, 2012 at 20:19
  • you are right , i got var availableTags = "['animal','usman lovely']"; in the source , so should i need to get it as "["animal","usman lovely"]" because original source has written it as it is ,hows that possible in C# ?I need my C# code to give C# code string like present here jqueryui.com/demos/autocomplete/#multiple , please let me know a method Commented Jan 27, 2012 at 7:21
  • Remove the double qutoes arount text i.e. var availableTags = <%=test%>. Then you can use that variable as an array in JavaScript Commented Jan 27, 2012 at 14:43
0

only use indexes to get your test string array i have tried by giving indexes like

var availableTags =  "<%=test[0]%>";  // animal 
var availableTags =  "<%=test[1]%>";  // lovely 
0

If you're doing an online coding challenge, the browser-based IDE might not let you use string.join, like with my job, which has us use iMocha.

Instead of that, I just created a StringBuilder object (from System.Text) and iterated over the array, appending each integer and a blank space, then converting the result to a string. Something like this:

var array = new int[] {1, 3, 5, 7, 9};
var str = new StringBuilder();
foreach (int i in array)
{
  str.Append(i);
  str.Append(" ");
}
var result = str.ToString();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.