Simply put, it is not possible to write C# code directly inside javascript. Javascript is a client-side scripting language, while C# is compiled code that runs on the server.
However, if you are using ASP.NET, you can include javascript in your page. Here is a basic 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 manipulate this javascript array on the client side:
<script language="javascript">
// Check if the array is available
if (typeof(myArray) != 'undefined' && myArray != null) {
alert(myArray[0]);
}
</script>
It is a straightforward process to convert a prepopulated list into a javascript array:
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);
}
}