Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through objects in ViewData via javascript on the page/view?

First off, I am fairly new to MVC and jQuery. I apologize if my question or terminology is incorrect.

I currently have a view in my MVC application that displays a list of addresses. On the same page, I also have a map where I wish to map these locations.

I am trying to find the 'proper' way of getting the list of address objects to the javascript in the view so that it may be iterated through and mapped.

I have seen some solutions which require a getJSON call to the controller from the javascript code. I wish to avoid this solution since it requires another trip to the database and webserver. All of the information that I need to render the addresses on the map is already being presented to the View via ViewData.

I have also seen a solution in which the javascript could access the data passed into the view via ViewModel.Data, however this example was working on a single object, as opposed to a list.

I would appreciate it if anyone had any tips or resources available.

Thanks

like image 917
Adam Avatar asked Mar 01 '23 22:03

Adam


1 Answers

Just render the data into your javascript. Say you have a list of address objects like this:

public class Address
{
    public string Line1 { get; set; }
    public string City { get; set; }
}

// in your controller code
ViewData["Addresses"] = new List<Address>(new Address[] { new Address() { Line1="bla", City="somewhere"}, new Address() {Line1="foo", City="somewhereelse"}});

Render it into your javascript like this:

<script type="text/javascript">
var addresses = new Array(
<% for (int i = 0; i < ViewData["Addresses"].Count; i++) { %>
<%= i > 0 : "," : "" %>({line1:"<%= addr.Line1 %>", city:"<%= addr.City %>"})
<% } %>);
</script>

This basically creates a JSON formatted array with your address objects in javascript.

UPDATE: If you want to do this automatically using the framework code instead of writing your own code to serialize to JSON, take a look at the JavaScriptSerializer. Here's a howto from the great ScottGu on doing this: Tip/Trick: Building a ToJSON() Extension Method using .NET 3.5

like image 86
Chris Hynes Avatar answered Mar 05 '23 18:03

Chris Hynes