2016-12-01 32 views
0

我正在使用vectormap以此格式獲取數據{「en 「:」600「,」ru「:200,...} 我在控制器中檢索數據,並創建一個VectorMapViewModel的列表並通過json結果傳入視圖並使用jquery獲取該數據,但是我無法爲矢量地圖創建此格式。如何傳遞json數據,如{「en」:「600」,「ru」:200,...}以在asp.net中查看控制器mvc

public class VectorMapViewModel 
{ 
    public string CountryCode { get; set; } 
    public int CountryVisit { get; set; } 


} 

[HttpGet] 
    public JsonResult RequestVisitorsVectorMapData() 
    { 
     var countrydata =new List<VectorMapViewModel>(); 
     using (var db = new AppDbContext()) 
     { 

      var results = db.Countries; 
      countrydata.AddRange(results.Select(country => new VectorMapViewModel 
      { 
       CountryCode = country.CountryCode, 
       CountryVisit = country.ViewCount 
      })); 
      return Json(countrydata, JsonRequestBehavior.AllowGet); 
     } 
    } 

<script> 

    $(window).load(function() { 
     $.getJSON('/Home/RequestVisitorsVectorMapData/', function(data) { 


      $('#world-map').vectorMap({ 
       map: 'world_en', 
       backgroundColor: null, 
       borderColor: '#000', 
       borderOpacity: 0.25, 
       borderWidth: 0.5, 
       color: '#e7eaeb', 
       enableZoom: true, 
       hoverColor: '#16a085', 
       normalizeFunction: 'polynomial', 
       scaleColors: ['#C8EEFF', '#006491'], 
       selectedColor: '#000', 
       values: data 
      }); 
     }); 

    }); 
</script> 

回答

1

將您的數據字典:

[HttpGet] 
public JsonResult RequestVisitorsVectorMapData() 
{ 
    var countrydata = new List<VectorMapViewModel> 
    { 
        new VectorMapViewModel { CountryCode = "us", CountryVisit = 100}, 
        new VectorMapViewModel { CountryCode = "ru", CountryVisit = 200}, 
        new VectorMapViewModel { CountryCode = "ir", CountryVisit = 2000} 
    }; 

    var dictionary = new Dictionary<string, int>(); 
    foreach (var item in countrydata) 
    { 
        dictionary.Add(item.CountryCode, item.CountryVisit); 
    } 

    return Json(dictionary, JsonRequestBehavior.AllowGet); 
} 

這本詞典將被序列化到:

{"us":100,"ru":200,"ir":2000} 
0

你可以這樣做:

$(window).load(function() { 
    $.getJSON('/Home/RequestVisitorsVectorMapData/', function(data) { 
     var struct = {}; 
     for(var i = 0; i < data.length; i++){ 
      struct[data[i].CountryCode] = data[i].CountryVisit; 
     } 

     $('#world-map').vectorMap({ 
      map: 'world_en', 
      backgroundColor: null, 
      borderColor: '#000', 
      borderOpacity: 0.25, 
      borderWidth: 0.5, 
      color: '#e7eaeb', 
      enableZoom: true, 
      hoverColor: '#16a085', 
      normalizeFunction: 'polynomial', 
      scaleColors: ['#C8EEFF', '#006491'], 
      selectedColor: '#000', 
      values: struct 
     }); 
    }); 

}); 
+0

謝謝您的回答但結構返回數據像{en = 600},但我想{en:600} –

+0

代碼會給你{en:600}。它正在做的就是用這些屬性創建一個對象。 – Steve

相關問題