I have a list of users which I pass from my controller to my view using the view bag. Now I need to be able to pass the same list to the javascript on the page. I could reconstruct the list using a foreach loop:
@foreach (var item in ViewBag.userList) //Gets list of users passed from controller and adds markers to the map
{
var userLat = item.LastLatitude;
var userLon = item.LastLongitude;
var _userId = item.Id;
<script>array.push({"userId":"'@_userId'","userLat":"'@userLat'","userLon":"'@userLon'"});</script>
}
However this seems like a messy approach and required a lot of reworking if a change is made. I know there are similar posts on Stack overflow, but a lot of them use previous version of MVC and the same syntax doesn't seem to apply. Any ideas?
You could do that in a single and safe line of code using a JSON parser. You should absolutely never manually build JSON with some string concatenations and stuff as you attempted to do in your example. No need to write any loops as well.
Here's the correct way to do that:
<script type="text/javascript">
var array = @Html.Raw(
Json.Encode(
((IEnumerable<UserModel>)ViewBag.userList).Select(user => new
{
userId = user.Id,
userLat = user.LastLatitude,
userLon = user.LastLongitude
})
)
);
alert(array[0].userId);
</script>
The generated HTML will look exactly as you expect:
<script type="text/javascript">
var array = [{"userId":1,"userLat":10,"userLon":15}, {"userId":2,"userLat":20,"userLon":30}, ...];
alert(array[0].userId);
</script>
Of course the next level of improvement in this code is to get rid of the ViewCrap
and use a strongly typed view model.