0

I have a list like this:

List<string> list = new List<string>(10);

list.Add("Foo");
list.Add("Bar");
list.Add("Tord");
list.Add("Bob");

How can i loop the list with JavaScript? And how can i write C# code inside JavaScript?

2
  • 1
    What platform is this for? I'm not sure you can mix-and-match languages like this in any environment I'm familiar with... Commented May 14, 2011 at 11:59
  • OK, first of all, why on earth do you want to write C# code inside your JavaScript? Is this a webapp? If you're using C# on your server and JavaScript in the browser, you need to get the data from the server to the client first, probably using JSON. You'll then have a JSON Array which you can loop over with JavaScript. As it is, the browser won't even be able to see that list. Commented May 14, 2011 at 12:00

4 Answers 4

5

Quite simply, you cannot write C# inside javascript - javascript is a scripting language executed on the client, and C# is compiled code that runs on the server.

If you are using ASP.NET you can output javascript to your page though, here is a very simple example:

void WebForm1_PreRender(object sender, EventArgs e)
{
    if (!ClientScript.IsClientScriptBlockRegistered("MyScript"))
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("var myArray = new Array();");
        sb.AppendLine("myArray[0] = 'some value';");
        sb.AppendLine("myArray[1] = 'another value';");
        sb.AppendLine("myArray[2] = 'yet another value';");

        ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", sb.ToString(), true);
    }
}

you can then access and iterate this javascript array on the client:

<script language="javascript">
    //first do basic check that the array is available:
    if (typeof(myArray) != 'undefined' && myArray != null) {
        alert(myArray[0]);
    }
</script>

From here it is a simple process to take your prepopulated list and create the javascript list:

void WebForm1_PreRender(object sender, EventArgs e)
{
    List<string> list = new List<string>(new[] { "Foo", "Bar", "Tord", "Bob" });

    if (!ClientScript.IsClientScriptBlockRegistered("MyScript"))
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("var myArray = new Array();");
        for (int i = 0; i < list.Count; i++)
            sb.AppendLine(string.Format("myArray[{0}] = '{1}';", i, list[i]));

        ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", sb.ToString(), true);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

you can use a method that creates the json data:

public static string CreateJsonArray(List<string> list)
{
    if (list.Count > 0)
    {
        StringBuilder sb = new StringBuilder();
        foreach (string item in list)
        {
            sb.AppendFormat("'{0}',", item);
        }
        sb.Remove(sb.Length - 1, 1);
        return String.Format("[{0}]", sb.ToString());
    }
    return "[]";            
}

and than assign it to a javascript script tag

// C#
List<string> list = new List<string>(10);

list.Add("Foo");
list.Add("Bar");
list.Add("Tord");
list.Add("Bob");

ltrResult.Text = CreateJsonArray(list);

// HTML
<script type="text/javascript">
    var arr = <asp:Literal id="ltrResult" runat="server" />;
</script>

Comments

0

@tord: at least for now, you cant use C# code in your javascript file. you would most probably need to convert you List<> to some json equivalent that your javascript can understand. You can use Response.Write from C# to send over the json to the client side

Comments

0

You could go with either injecting the list as an javascript list from your codebehind or if you also whant to show the list you coudl do something simple as:

Front

<asp:Label runat="server" ID="showList"></asp:Label>

Code behind

            List<String> list = new List<string>();
            list.Add("Hello");
            list.Add("How are you doing");
            list.Add("Fine and you?");

            showList.Text += "<ul id='jList'>";
            foreach(String val in list){
                showList.Text += "<li>" + val + "</li>";
            }
            showList.Text += "</ul>";

Then you can access the "jList" from within javascript by GetElementByNode..

Comments

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.