Saturday, January 1, 2011

Passing Data from ViewModel to Javascript on the View

Option 1: construct the javascript into a string put it directly into the ViewData
ViewData["clientScript"] = "<script type='text/javascript'>initialize();addOverLay(-34.397, 150.644)</script>";

<%=ViewData["clientScript"]%>

This is of course prone to javascipt attacks

Option 2: Convert to Json(InfoList is of type string)

var js = new JavaScriptSerializer();
var listOfInfos = new List<string> {"abc", "cde"};

var viewModel = new InfoModel
               
{
                   
InfoList = js.Serialize(listOfInfos);
               
};
return View(viewModel);

In the View
   <script type="text/javascript">
      var result = <%= Model.InfoList%>
   </script>

No comments:

Post a Comment