How to share arrays between code behind and javascript with RegisterStartupScript and RegisterArrayDeclaration

These two methods of Page in ASP.NET allow you to programmatically insert Javascript code into your code behind. Basically, you could do everything with RegisterStartupScript but the RegisterArrayDeclaration method gives you an easy way to insert arrays so that your code behind can share arrays with your Javascript code. Notice that since I used a string array in this example, that I needed to add a single quote to either side of my array elements.
<%@ Page Language="C#" Debug="true" %>
<script runat="server">

void Page_Load(Object sender, EventArgs e)
String scriptString = "\n";
scriptString += "<script language=JavaScript>\n";
scriptString += "<" + "!--\n";
scriptString += "    function showIds() {\n";
scriptString += "        for(var index=0;index < ids.length;index++)\n";
scriptString += "        document.write(ids[index] + '<br>');\n";
scriptString += "    }\n";
scriptString += "//-->\n";
scriptString += "<" + "/" + "script>\n";

RegisterStartupScript("arrayScript", scriptString);

string[] ids = {"111","112","the third one","114"};
RegisterArrayDeclaration("ids","'" + String.Join("','",ids) + "'");


Post a Comment


Close Menu