将数组或字符串 [] 的 C# 字符串分配给 javascript 数组 [英] assign C# string of array or string[] to javascript array

查看:21
本文介绍了将数组或字符串 [] 的 C# 字符串分配给 javascript 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 js 代码,其中一个数组在它像

var availableTags = ["动作脚本","AppleScript","阿普",基本的",C"];

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

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

然后我把js数组改成了这个

 var availableTags = "<%=test%>";//也试过不加引号

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

使用完整代码进行编辑,我从 http://jqueryui.com/中获取的 jquery演示/自动完成/#multiple

 使用系统;使用 System.Collections.Generic;使用 System.Linq;使用 System.Web;使用 System.Web.UI;使用 System.Web.UI.WebControls;使用 System.Collections;使用 System.Web.Script.Serialization;公共部分类 onecol : System.Web.UI.Page{JavaScriptSerializer 序列化器;public static string test = "['animal','lovely']";公共静态字符串检查;protected void Page_Load(object sender, EventArgs e){serializer = new JavaScriptSerializer();//序列化器this.detail.ToolsFile = "BasicTools.xml";测试 = returnTitle();}}

和 html 的脚本是

<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">$(函数(){var availableTags = <%=test%>;函数拆分(val){返回 val.split(/,s*/);}函数extractLast(term) {返回 split(term).pop();}$("#tags")//选择项目时不要离开选项卡上的字段.bind("keydown", 函数(事件){if (event.keyCode === $.ui.keyCode.TAB &&$(this).data("autocomplete").menu.active) {event.preventDefault();}}).自动完成({最小长度:0,来源:功能(请求,响应){//委托回自动完成,但提取最后一项响应($.ui.autocomplete.filter(availableTags,extractLast(request.term)));},焦点:函数(){//防止在焦点上插入值返回假;},选择:功能(事件,用户界面){var term = split(this.value);//移除当前输入条款.pop();//添加选中的项目条款.push(ui.item.value);//添加占位符以获取末尾的逗号和空格条款.push("");this.value = term.join(", ");返回假;}});});</asp:内容><asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="服务器"><div class="demo" ><div class="ui-widget"><label for="tags">标记编程语言:</label><input id="Text1" class="#tags" size="50"/>

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

解决方案

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

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

通常我会创建一个简单的静态类作为包装器.

公共静态类 JavaScript{公共静态字符串序列化(对象 o){JavaScriptSerializer js = new JavaScriptSerializer();返回 js.Serialize(o);}}

然后你可以使用那个类来序列化你需要的项目

//C#数组(asp页面成员)protected string[] Values = { "Sweet", "Awesome", "Cool" };<script type="text/javascript">var testArray = <%=JavaScript.Serialize(this.Values) %>

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 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

解决方案

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>

这篇关于将数组或字符串 [] 的 C# 字符串分配给 javascript 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆