【问题标题】:Passing c# values from controller to view javascript从控制器传递 c# 值以查看 javascript
【发布时间】:2018-03-28 03:21:49
【问题描述】:

所以我试图从控制器列表中传递纬度和经度值以查看脚本(谷歌地图)。这段代码的目的是根据控制器的经纬度列表在谷歌地图上创建多个标记。

如何将列表从控制器实际传递到谷歌地图的查看脚本?

这是我的一些代码:

index.cshtml

<script> 
@foreach (float list in ViewBag.latitude_list){
@foreach (float list2 in ViewBag.longitude_list){
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(@list, @list2),
            map: map,
            title: 'Hello World!'
        });
    }
}
</script>

controller.cs

//add latitude and longitude to list                        
latitude_list.Add(entity.vehicle.position.latitude);
longitude_list.Add(entity.vehicle.position.longitude);

ViewData["latitude_list"] = latitude_list;
ViewData["longitude_list"] = longitude_list;
return View();

我对此还是很陌生,任何帮助将不胜感激。

更新

这就是我用 C# 值填充 javascript google map lat 和 lng 的方式。 与模型,

homecontroller.cs

latLngList.Add(new LatLng() {Lat = entity.vehicle.position.latitude, Lng = entity.vehicle.position.longitude})

index.cshtml

<script>
var markersArray = [];

    @foreach (var item in ViewBag.latLngList){
       <text>
             markersArray.push(new google.maps.Marker({
                 draggable: true,
                 position: new google.maps.LatLng('@item.Lat', '@item.Lng', false),
                 title: 'Whatever title',
                 map: map
             }));
        </text>
    }
</script>

【问题讨论】:

  • 如果我理解正确,您应该使用模型。
  • 您可以对控制器操作进行 ajax 调用,并使用直接映射到 c# 模型的 JSON 来回传递值。
  • 您有一个包含属性double Longitudedouble Latitude 的模型,您将该模型的集合传递给视图并使用var data = @Html.Raw(Json.Encode(Model)) 将其转换为javascript 数组

标签: c# asp.net asp.net-mvc


【解决方案1】:

如果我正确理解您的问题,答案将是:

  • 您可以创建具有两个属性 Lat 和 Lng 的模型。
  • 然后创建一个要传递给视图的位置列表。
  • 我认为代码应该是这样的。

LatLng.cs

public class LatLng
{
public float Lat {get;set;}
public float Lng {get;set;
}

controller.cs

//add latitude and longitude to list
public class Controller
{
List<LatLng> latLngList = new List<LatLng>();
latLngList.Add(new {entity.vehicle.position.latitude, 
entity.vehicle.position.longitude} );
ViewData["latLng_List"] = latLngList;
return View();
}

index.cshtml

<script> 
@foreach (var item in ViewData["latLng_List"] as IList<>){
   var marker = new google.maps.Marker({
   position: new google.maps.LatLng(item.Lat, item.Lng),
   map: map,
   title: 'Hello World!'
   });
}
</script>
  • 有很多方法可以做到这一点,但我会根据你的回答来做。

【讨论】:

  • 所以我实际上有两个单独的列表,用于纬度和经度。那么它会是一个嵌套的@foreach 吗?抱歉,我对此还是很陌生。能否请您举例说明如何执行此操作?
  • @Student04 为什么你会有两个单独的 lat 和 lng 列表,最好的做法是创建一个列表(Lat 和 Lng 作为对象)并将其传递给查看。但我会编辑我的答案,为您提供与您的代码相关的另一个选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-27
  • 1970-01-01
  • 1970-01-01
  • 2015-12-27
  • 2020-04-11
  • 2021-04-19
  • 1970-01-01
相关资源
最近更新 更多