-2

i wrote this code to pass array from asp.net code to javascript:

aspx File:

<script type="text/javascript">
    var loc_array;
    var loc_array_two;
    function AssignValues(loc, loc_two){
        loc_arary= loc;
        loc_array_two = loc_two;
        alert(loc_array[0]);
    }
</script>

aspx.cs File:

StringBuilder sb = new StringBuilder();
sb.Append("var loc = [");
foreach (var str in lb1)   //lb1 is list
{
    sb.Append("['" + str.Value1 + "','" + str.Value2 + "','" + str.Value3 + "'],");
}
sb.Append("];");
StringBuilder sb2 = new StringBuilder();
sb2.Append("var own = [");
foreach (var str2 in lb2)   //lb2 is list
{
    sb2.Append("['" + str2.Value1 + "','" + str2.Value2 + "','" + str2.Value3 + "'],");
}
sb2.Append("];");

if (lb1.Count > 0 && lb2.Count > 0)
{
    string arrayStr1 = string.Format("[{0}]", sb.ToString().TrimEnd('{','}'));
    string arrayStr2 = string.Format("[{0}]", sb.ToString().TrimEnd('{', '}'));
    Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "AssignValues(" + arrayStr1 + "," + arrayStr2 + ")", true);
}

The array that created is [var loc = [['New York','33.6306686','73.1175653'],];] - Now this array passed to the function of javascript. But nothing prints. Can anyone help me to solve this problem.

3
  • 2
    You should probably update your post; show the entire method (including it's name) of your .cs file. Then how you call this methods from your .js (probably your ajax call). Is AssignValues (your js) ever called? Commented Dec 2, 2014 at 16:01
  • @sander the AssignValues function is working fine without parameters. But on passing arrays as parameter to this function it shows nothing. Commented Dec 3, 2014 at 5:14
  • Plz try what I suggested before. You are also not passing any arrays, you are passing strings. What you probably want is JSON and you are in luck, .NET has ways of sending JSON to the frontend! stackoverflow.com/questions/227624/… Commented Dec 3, 2014 at 10:02

1 Answer 1

1

why don't you use this form?

var yourjavascriptArray = <%=new JavaScriptSerializer().Serialize(cSharpArrayName);%>;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.