Trying to iterate through a list of strings and display them on the page, but facing an error as described in the title...
"Uncaught TypeError: response.forEach is not a function"
I've looked into for loops in JavaScript, but they seem to work with arrays. As a JavaScript novice, I'm wondering if there is an equivalent .ToArray() method in JavaScript that I can use? I have created a simple application to demonstrate my goal.
Note: The return type of the controller method "GetStringList" cannot be changed. In the larger application, the method must return a list of strings.
Controller Method (C#)
public List<string> GetStringList(){
List<string> listOfStrings = new List<string>();
SqlConnection sqlConn = new SqlConnection(connection_String);
sqlConn.Open();
string sqlStr = "SELECT * FROM dbo.[SampleOrders] WHERE Active = 1";
SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
SqlDataReader sqlDR = sqlCmd.ExecuteReader();
if (sqlDR.HasRows) {
while (sqlDR.Read()) {
listOfStrings.Add((string)sqlDR["SalesOrder"]);
}
}
sqlDR.Close();
sqlCmd.Dispose();
sqlConn.Close();
return listOfStrings;
}
View / JavaScript Function
<script>
$(document).ready(function () {
$('#demoBtn').click(function () {
$.ajax({
type: 'GET',
url: '/Home/GetStringList',
success: function (response) {
response.forEach(function (item) {
alert(item);
});
}
});
});
});
</script>
Any clarifications needed, please feel free to ask - appreciate your help!