2011-11-27 123 views
0

我必须在runtime.The生成脚本的文本生成控制器类一个javascript:动态JavaScript 3.0 +剃须刀

private string mapString 
{ 
    get 
    { 
     Locations loc = new Locations(); 
     string appPath = Request.ApplicationPath; 
     loc.ReadXml(Path.Combine(Request.MapPath(appPath) + "\\App_Data", "Locations.xml")); 
     StringBuilder sb = new StringBuilder(); 
     for (int i = 0; i < loc.Specfications.Count; i++) 
     { 
      sb.Append("var myLatLng" + i.ToString() + "= new google.maps.LatLng(" + loc.Specfications[i].Y.ToString() + "," + 
      loc.Specfications[i].X.ToString() + ");"); 
      sb.Append(" var beachMarker" + i.ToString() + " = new google.maps.Marker({position: myLatLng" + i.ToString() + ",map: map,icon: image,title:'" + loc.Specfications[i].Title + "'});"); 

.... 

... 

... 

     ViewData["MapString"] = mapString; 

当我使用它在脚本标签:

<script type="text/javascript"> 

       function initialize() { 
       @Server.HtmlDecode(ViewData["MapString"].ToString()) 

       } 

</script> 

忽略了最低,还原一个真实的文字,它retruns是这样的:

contentString0 = ' <表格宽度= " 100%" style = " font-family:tahoma; text-align:right;字体

**更新:该网站没有正确显示我的问题,我想显示“' <”,但它显示“” <”

但它必须返回: contentString0 =' 你请参阅它将“'<”转换为“' <”。 但是,当我使用:@ Server.HtmlDecode(ViewData [“MapString”]。ToString())出脚本标记,所有的事情都可以。

+1

首先为什么你需要在你的控制器中生成你的javascript?据我所见,你可以将经度和纬度传递给Goole Maps API。为什么不创建一个Controller操作,只返回需要的数据作为JSON对象? – torm

+0

我该怎么做呢?你能举一个例子吗?是的,我想在谷歌地图dyanmicaly上做记号。 – Shayan

回答

1

您可能需要做这种方式,我认为这将是比你的控制器生成的代码更加灵活:

控制器动作:

public JsonResult GetCoords() 
    { 
     // your code here - im putting a generic result you may 
     // need to put some logic here to retrieve your location/locations 

     var result = new { lon = "51.0000", lat = "23.0000" }; 
     return Json(result, JsonRequestBehavior.AllowGet); 

    } 
在视图中添加

<script type="text/javascript"> 
     $(document).ready(function() { 

      $.getJSON('/YourController/GetCoords', function (jsonData) { 

       var lon = jsonData.lon; 
       var lat = jsonData.lat; 

       yourGoogleMapFunction(lon, lat); 

      }); 
     }); 
    </script> 
+0

您示例中的getJSON工作。我从JQuery网站下载JQery1.7.js,但示例没有工作。 – Shayan

+0

请告诉我你的代码,所以我可以帮助你 – torm

+0

在我的控制器类:[HttpPost] 公共JsonResult GetCoords(){ // 您在这里的代码 - 即时把一个通用的结果时可能 //需要把一些逻辑在这里检索您的位置/位置 var result = new {lon =“51.0000”,lat =“23.0000”}; return Json(result,JsonRequestBehavior.AllowGet); } – Shayan