Well, if you use only a list of strings, then
it will do
$(document).ready(function () { @{List<string> listFromController = (List<string>)ViewData["List"];} var myArray = [ @for (int i = 0; i < listFromController.Count; i++) { @: '@(listFromController[i])', } ] });
But if you are passing a list of a different type, and not a string, such as an Employee student or user, you will need the following
Please use the appropriate class that you passed, and the properties suggest that "UserName" could be "FirstName", "EmpId" or someday
$(document).ready(function () { @{ var listFromController = (List<KnockoutJSWebApi.Models.LoginViewModel>)ViewData["list"];} var totalArray = []; @for (int i = 0; i < listFromController.Count; i++) { <text> var thisArray= { 'username': '@(listFromController[i].UserName)', 'password': '@(listFromController[i].Password)' }; totalArray.push(thisArray); </text> } });
Syntax for Aspx View Engine:
<script> $(document).ready(function () { <% List<string> listFromController = (List<string>)ViewData["List"]; %> var myArray = [ <% for (int i = 0; i < listFromController.Count; i++){ %> '<%: listFromController[i] %>', <% } %> ] debugger; }); </script>
source share