I have a situation where I am passing a list of users from my controller to the view using the ViewBag. Now, I also need to pass this same list to the JavaScript on the page. One way I thought of doing this is by iterating through the list with a foreach loop:
@foreach (var user in ViewBag.userList)
{
var userLat = user.LastLatitude;
var userLon = user.LastLongitude;
var userId = user.Id;
<script>array.push({"userId":"'@userId'","userLat":"'@userLat'","userLon":"'@userLon'"});</script>
}
However, I feel like this approach is not very clean and would require extensive reworking if any changes are made later on. I have checked similar posts on Stack Overflow, but they seem to be using older versions of MVC with different syntax. Any suggestions on a better way to achieve this?