简体   繁体   English

用c#填充javascript数组

[英]Fill javascript array with c#

How Can i fill an array that defined in javascript with c# in behind code? 如何在后面的代码中用c#填充javascript中定义的数组?

EDIT: 编辑:

here is my code 这是我的代码

protected void Page_Load(object sender, System.EventArgs e)
{
string[] locations = new string[] {
    "Las Vegas",
    "Los Angeles",
    "Tampa",
    "New York",
    "s",
    "sss"
};
string jsArray = GetJSArrayForVBArray(locations);
this.ClientScript.RegisterArrayDeclaration("usernames", jsArray);
}

private string GetJSArrayForVBArray(string[] vbArray)
{
StringBuilder myResult = new StringBuilder();
foreach (string item in Constants.vbArray) {
    {
        myResult.Append(",'" + item + "'");
    }
}
if ((myResult.Length > 0)) {
    return myResult.ToString().Substring(1);
} else {
    return "";
}
}

Javsacript: Javsacript:

<script type="text/javascript">
    $(function () {
        var usernames = new Array();
        $("#tags").autocomplete({
            source: usernames
        });
    });
</script>

use the JavaScriptSerializer class. 使用JavaScriptSerializer类。 Something like the following should do it 像下面这样的东西应该这样做

protected void Page_Load(object sender, System.EventArgs e)
{
    string[] locations = new string[] {
        "Las Vegas",
        "Los Angeles",
        "Tampa",
        "New York",
        "s",
        "sss"
    };

    JavaScriptSerializer serializer = new JavaScriptSerializer();

    string jsArray = serializer.Serialize(locations);
    this.ClientScript.RegisterClientScriptBlock(this.GetType(), "locations", jsArray, true);
}

Sounds like a job for JSON . 听起来像是JSON的工作。 Note that if you scroll down on that page you'll see a number of resources for utilizing JSON in C#. 请注意,如果向下滚动该页面,您将看到许多用于在C#中使用JSON的资源。 It's really a great way to transfer data back and forth between various platforms/languages. 这是在各种平台/语言之间来回传输数据的绝佳方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM