将数组或字符串 [] 的 C# 字符串分配给 javascript 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9023972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:38:58  来源:igfitidea点击:

assign C# string of array or string[] to javascript array

c#javascriptjqueryasp.netjquery-ui

提问by user1074474

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

我有一个 js 代码,其中一个数组在它喜欢时运行良好

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

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

然后我在我的代码后面或 .cs 中创建了一个数组字符串,就像在类级别

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

I then changed js array to this

然后我将 js 数组更改为此

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

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

现在我没有像以前的 js 数组那样得到结果

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

使用完整代码进行编辑,我从http://jqueryui.com/demos/autocomplete/#multiple获取的 jquery

  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

和 html 的脚本是

<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

实际上它是一个自动完成功能来提供标签,我想从 C# 代码中获得的自动完成标记建议,我从 jqueryui.com/demos/autocomplete/#multiple 获取了 Jquery 源代码,然后我尝试从 . cs 文件,我用编辑版本的代码解释了它,后面的 C# 代码与链接中的完全一样

采纳答案by Brian

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

您需要将 C# 字符串数组序列化为 javascript 数组。

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

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>

回答by ShankarSangoli

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

testproperty 应该是一个字符串属性,它应该呈现将由 Js 引擎解析为数组的字符串。尝试这个。

Code behind property

财产背后的代码

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

JS

JS

 var availableTags =  <%=test%>;//No quotes

回答by amit_g

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.

两者都适合自动完成。

回答by James Montagne

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

回答by Zare Ahmer

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