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

First off, I'm pretty new to MVC and jQuery. We 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 on which I want to map these locations.

I am trying to find the "right" way to get a list of address objects in javascript in a view so that it can be repeated and displayed.

I saw some solutions that require a getJSON call to the controller from javascript code. I want to avoid this solution as it requires another trip to the database and web server. All the information that I need to display the addresses on the map is already presented in the view via ViewData.

I also saw a solution in which javascript could access the data passed to the view through ViewModel.Data, however this example worked on a single object, as opposed to a list.

I would appreciate if anyone had any advice or resources.

thanks

+4
source share
3 answers

Just visualize the data in your javascript. Let's say you have a list of addressable 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"}}); 

Paste it into your javascript as follows:

 <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 frame code instead of writing your own code for serialization in JSON, take a look at JavaScriptSerializer. Here's how to do it from the great ScottGu: Tip / Trick: creating a ToJSON () extension method using .NET 3.5

+5
source

Technically, ViewData does not display HTMl output, so it will not be sent to the client browser. The only way you can access ViewData is to render it for an object in an array like HTML, or something like:

 var cityList = new Array(); function addCity(cityId, cityName) { var city = new Object(); city.CityID = cityId; city.CityName = cityName cityList .push(city); } <% foreach (Something.DB.City item in ViewData["Cities"] as List<City>) { %> addCity(item.Id, item.Name); <% } %> 

This is what I usually do when I need to display data for javascript

+2
source

You can format the data in JSON on the server (as a string). Assign this to your ViewData. Then, in the ViewData view, set the ViewData variable to the value of the javascript variable.

 <script type="text/javascrpt"> var objList = <%= ViewData["objectListJSON"]; %>; for (var obj in objList) { ... } </script> 
+1
source

All Articles