Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill javascript array with c#

How Can i fill an array that defined in javascript with c# in behind code?

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:

<script type="text/javascript">
    $(function () {
        var usernames = new Array();
        $("#tags").autocomplete({
            source: usernames
        });
    });
</script>
like image 584
Shahin Avatar asked Aug 07 '10 09:08

Shahin


2 Answers

use the JavaScriptSerializer class. 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);
}
like image 165
Russ Cam Avatar answered Sep 29 '22 13:09

Russ Cam


Sounds like a job for JSON. Note that if you scroll down on that page you'll see a number of resources for utilizing JSON in C#. It's really a great way to transfer data back and forth between various platforms/languages.

like image 20
Jeffrey Blake Avatar answered Sep 29 '22 11:09

Jeffrey Blake