you should convert your c# array into javascript readable formate using
var array = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(this.Givenome)%>;
then you can iterate through javascript object
for (var x = 0; x < array.length; x++)
{
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = array[x];
cell2.innerHTML = "NEW CELL2";
}
I think what you want is something like this:
var table = document.getElementById('myTable');
<%
for (var i = 0; i < Givenome.Length; i++)
{
Response.Write("{");
Response.Write("var row = table.insertRow(0);");
Response.Write("var cell1 = row.insertCell(0);");
Response.Write("var cell2 = row.insertCell(1);");
Response.Write("cell1.innerHTML = '" + Givenome[i] + "';");
Response.Write("cell2.innerHTML = 'NEW CELL2';");
Response.Write("}");
}
%>
I want to include the variable “count” inside the ‘<%:Givenome[count]%>’ code.
HTML code
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
</table>
<br>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var count;
for (count = 0; count < <%=Givenome.Count()%>; count++)
{
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "<%:Givenome[count]%>";
cell2.innerHTML = "NEW CELL2";
}
}
</script>
This is my C# Code, where I create my string array.
public string[] Givenome { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
string[] answers = new string[10] { "Y", "Y", "N", "Y", "N", "Y", "N", "Y", "N", "Y" };
Givenome = answers;
}
What if Givenome is a million items long? You really want to inject that block a million times in the HTML? Also, the OP wrapped it in a JavaScript function, presumably to call it from different places. Lastly (also relates to OP’s code): JS has function level scoping of vars, so you shouldn’t use them like this. I wouldn’t recommend this answer.
No, I don’t, but this is the answer to his question. I’m afraid there is no other simple and direct way to address that. Scoping is irrelevant for this, as we are not concerned about that.
Scoping indeed is irrelevant, was just pointing it out, as it becomes more apparent in your repeating code, as it was in OP’s block level for-loop. However, my main point is: don’t use code to generate code. It’s a sustainability nightmare and something that should be avoided at all cost. Use code to generate data as in @swagat raorane ‘s answer.