Reputation: 612
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
Upvotes: 4
Views: 13058
Reputation: 54
Technically, ViewData is not render to output HTMl thus will not be sent to client browser. The only way you can access to ViewData is render it to an object in the HTML like array 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's the way I usually do when I need to render data for javascript
Upvotes: 2
Reputation: 10239
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
Upvotes: 5
Reputation: 532455
You could format the data in JSON on the server (as a string). Assign this to your your ViewData. In your View then, assign the ViewData to a javascript variable.
<script type="text/javascrpt">
var objList = <%= ViewData["objectListJSON"]; %>;
for (var obj in objList)
{
...
}
</script>
Upvotes: 1