\\code public ActionResult mapPartial(DataTable dt) { string strEvents = "["; foreach (DataRow row in dt.Rows) { strEvents += "[" + row["Lat"].ToString() + "," + row["Long"].ToString() + "," + "\"" + row["LastName"].ToString() + row["DateOfBirth"].ToString() + "\"" + "],"; } strEvents = strEvents.Remove(strEvents.LastIndexOf(",")); strEvents += "]"; ViewBag.locpoints = strEvents; return PartialView(dt); } //in the partial view page <script type="text/javascript"> function mapInit(Viewbag.locpoints) { var arr = $.parseJSON(Viewbag.locpoints); //more code which assigns a map to div map below } </script> <div id="map" class="map"></div>
当加载部分视图时,如何立即调用JS函数来渲染我的地图.控制器中的partial方法返回一个用作JS函数中的参数的字符串.希望是有道理的.
解决方法
因为你似乎使用JQuery为什么不:
<script type="text/javascript"> $(document).ready(function(){ var arr = $.parseJSON("@Viewbag.locpoints"); //more code which assigns a map to div map below }); </script>
我也改变了你如何引用你的ViewBag值,因为你拥有它的方式,它不会是JavaScript中的字符串字面值.
另外,作为附注,请考虑使用JSON序列化程序将您的数据转换为JSON.如上所述,手动执行它被认为是不好的做法.