代码之家  ›  专栏  ›  技术社区  ›  Zeliax

MVC Razor变量已为ViewModel双变量删除“”

  •  0
  • Zeliax  · 技术社区  · 7 年前

    我有一个 PartialView 使用我的 ViewModel LatLonSpeedViewModel

    LatLonSpeedViewModel:

    public class LatLonSpeedViewModel
    {
        public double lat { get; set; }
        public double lon { get; set; }
        public double sp { get; set; }
    }
    

    @model List<LatLonSpeedViewModel>
    
    <div id="map"></div>
    
    <script>
        function initMap(){
            ... setting map code
    
            var geojson = []
    
            @foreach (var item in Model) {
                @:geojson.push(@(item.lat), @(item.lon), @(item.sp));
                //This is not how I generate my geojson object, but just for illustration
            }
        }
    </script>
    

    我的问题是,双变量中的点似乎被截断/删除。

    如果我做一个 @:console.log(@(item.lat)); @:console.log(@(item.lon)); 它将变量打印为 5 32145131 75 3215131 。如何修复此错误?

    2 回复  |  直到 7 年前
        1
  •  0
  •   RAHUL S R    7 年前

    只需将模型设为json对象

    <script>
    var jsonData = @Html.Raw(Json.Encode(Model));
    
    $(jsonData).each(function(){
    //Whatever you want 
    })
    </Script>
    
        2
  •  0
  •   Zeliax    7 年前

    @inject IJsonHelper Json;
    

    给我的 _ViewImports.cshtml

    然后我可以执行以下操作来迭代我的数据:

    var jsonData = @Html.Raw(Json.Serialize(Model));
    $.each(jsonData, function(key, value) {
        geojson.push(value.lat, value.lon, value.sp);
        //as with the question this is not how I add to my 
        //geojson object, but merely for illustration of how
        //to access the values
    });