I am coding a MVC 5 internet application and would like to know how to pass values from a ViewModel
into a jQuery
function where I have a list of data to pass.
Usually, I would create a hidden
field in the MVC
View
code, and then retrieve this value in the jQuery
code. However, in this situation, there is not just one value from the ViewModel
, but a List
of objects, where each object has many values.
My ViewModel
has a List<MapMarker>
, where each MapMarker
has the following attributes:
This is the jQuery
function that I need to call for each MapMarker
object:
function LoadMapMarker(latitude, longitude, title, draggable)
How can I call the LoadMapMarker
function, with data from each of the MapMarker
objects in the ViewModel
list?
Thanks in advance
You can serialize your list and storage it in a hidden field. Then call LoadMapMarker by means of Javascript on client side.
Server:
using System.Web.Script.Serialization;
var MapMarkers = new List<MapMarker>();
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(MapMarkers);
return View(new MyViewModel({JsonList = json }));
View:
<input type="hidden" id= "MyHiddenFieldForMapMarker" value="@Model.JsonList" >
Client:
var MapMarkers = $("#MyHiddenFieldForMapMarker").val();
for (var MapMarker in MapMarkers) {
LoadMapMarker(MapMarker["latitude"],
MapMarker["longitude"],
MapMarker["title"],
MapMarker["draggable"]);
}