2011-11-27 212 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