use*_*420 12 javascript asp.net-mvc partial-views
\\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>
Run Code Online (Sandbox Code Playgroud)
在加载局部视图时,如何立即调用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>
Run Code Online (Sandbox Code Playgroud)
我还更改了您引用ViewBag值的方式,因为您拥有它的方式,它不会是 JavaScript 中的字符串文字。
此外,作为旁注,请考虑使用 JSON 序列化程序将您的数据转换为 JSON。像上面那样手动执行被认为是一种不好的做法。
定义好之后,就可以调用它了。但是,您似乎在 JS 函数定义中包含了 MVC Viewbag 值。当您调用 JS 方法时,您应该传递这些值:
<script type="text/javascript">
function mapInit(locPoints) {
var arr = $.parseJSON(locPoints);
//more code which assigns a map to div map below
}
mapInit(@(Viewbag.locpoints));
</script>
Run Code Online (Sandbox Code Playgroud)
注意:这假设您已加载 jQuery。
| 归档时间: |
|
| 查看次数: |
37043 次 |
| 最近记录: |