【问题标题】:Asp net core MVC: Passing a list of string as a parameter in javascriptAsp net core MVC:在javascript中将字符串列表作为参数传递
【发布时间】:2016-12-17 12:06:06
【问题描述】:

我正在使用 google api 来显示地图。在我的控制器中,我编写了以下 c# 代码:

var sedi = new List<string>();
sedi.Add("Via Gavinana, 19, Roma");
sedi.Add("Val de Seine, 94600 Choisy le Roi");
sedi.Add("Street 21,Shuwaikh, Kuwait");
ViewBag.sediList = sedi;
return View(ViewBag.sediList);

在我看来:

@{
    var vb  = (List<string>)ViewBag.sediList;
}
function GetLatLon (address, callback) {
    console.log(address);
    var location = new Array();
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == 'OK') {
            location = { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() };
            callback(location);
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

function addMarker (location, map) {
    var marker = new google.maps.Marker({
        position: location,
        map: map
    });
}

function initMap() {
    GetLatLon("@vb", function(location) {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 2,
            center: location
        });
        for (var i = 0; i < 3; i++) {
           addMarker(location, map);
        }
    });
  }

我想在地图上显示三个标记,对应于列表中写入的位置vb 但是地址有System.Collections.Generic.List1[System.String] 值而不是地址的实际值。 如何将列表作为参数传递给 Javascript 中的 GetLatLon 函数?我该如何解决?

编辑

我需要在地图上显示三个标记,foreach 地址。 我写:

function GetLatLonByAddress (address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == 'OK') {
            location = { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() };
            return location;
            console.log (location);
        } 
        return;
    });
}

function initMap() {
    GetLatLon('@(new Microsoft.AspNetCore.Html.HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(Model‌​.Maps)))', function(location) {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 2,
            center: location
        });
        for (var i = 0; i < 3; i++) {
           addMarker('@(new Microsoft.AspNetCore.Html.HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(Model‌​.Maps)))', map, i);
        }
    });
  }

function addMarker (location, map, count) {
    var locationArr = JSON.parse(location);
    var marker = new google.maps.Marker({
        position: GetLatLonByAddress(locationArr[count]),
        map: map
    });
}

有可能是这样的吗?我该如何解决?

【问题讨论】:

  • 返回视图(ViewBag.sediList); - 看起来有点奇怪。如果您使用 ViewBag 并且 View 上没有模型 - 您需要返回 View()。如果有一个模型,包含 sediList - 那么你不需要 ViewBag。只需通过模型传递数据
  • GetLatLon("@vb", function(location) - 这里传递的是字符串,而不是数组
  • 您需要将其分配给 javascript 变量 - var vn = '@Html.Raw(Json.Encode(ViewBag.sediList))';,这将是您的 3 个地址字符串的数组。但是将代码更改为删除 ViewBag.sediList = sedi; 并使用 return View(sedi); 并在视图中添加 @model List&lt;string&gt; 然后使用 '@Html.Raw(Json.Encode(Model))';
  • @FabioBit System.Web.Mvc
  • @FabioBit,mvc核心请参考this answer

标签: javascript c# arrays list asp.net-core-mvc


【解决方案1】:

所以你可以创建:

型号

public class MapsModel
{
    public MapsModel(string[] maps)
    {
        Maps = maps;
    }

    public string[] Maps { get; private set; }
}

控制器

public class MapsController : Controller
{
   // GET: MapsModel
   public ActionResult Index()
   {
        var model = new MapsModel(
                new[]
                {
                    "Via Gavinana, 19, Roma",
                    "Val de Seine, 94600 Choisy le Roi",
                    "Street 21,Shuwaikh, Kuwait"
                } 
            );

      return View(model);
   }
}

查看

@model WebApplication1.Models.MapsModel

...

function initMap() {
   GetLatLon('@Html.Raw(Json.Encode(Model.Maps))', function (location) {

...

在这种情况下,您不需要 ViewBag。

【讨论】:

  • 您可以尝试使用一些 3rd-party,例如 '@Newtonsoft.Json.JsonConvert.SerializeObject(Model.Maps)'
  • 因为它返回字符串,而不是 HtmlString。应该有一种 HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Maps))... JsonHelper.Serialize 也应该解决这个问题。它应该是 Asp.net core v5 的一部分
  • GetLatLon('@(new HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Maps)))', 函数(位置){
  • 它返回什么样的字符串?我有 ["Via Gavinana, 19, Roma","Val de Seine, 94600 Choisy le Roi","Street 21,Shuwaikh, Kuwait"] 用于新的 HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(Model‌​.Maps))
  • 这只是一个数组... var array = ["Via Gavinana, 19, Roma","Val de Seine, 94600 Choisy le Roi","Street 21,Shuwaikh, Kuwait"]; for (var s in array) { document.write(array[s]); }
【解决方案2】:

您没有遵循最佳方法,但您可以使用此快速解决方案。

控制器:=>

var sedi = new List<string>();
sedi.Add("Via Gavinana, 19, Roma");
sedi.Add("Val de Seine, 94600 Choisy le Roi");
sedi.Add("Street 21,Shuwaikh, Kuwait");
ViewBag.sediList = Json.Encode(sedi);

// No need to pass the viewbag in View param
return View();

查看:=>

 var vb = @ViewBag.sediList;
 for(var i=0;i<vb.length;i++){
  GetLatLon (vb[i],function(){});
 }

 function GetLatLon (address, callback) {
    console.log(address);
    var location = new Array();
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == 'OK') {
            location = { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() };
            callback(location);
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

function addMarker (location, map) {
    var marker = new google.maps.Marker({
        position: location,
        map: map
    });
}

function initMap() {
    GetLatLon("@vb", function(location) {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 2,
            center: location
        });
        for (var i = 0; i < 3; i++) {
           addMarker(location, map);
        }
    });
  }

【讨论】:

    【解决方案3】:

    你必须像这样使用它: 在您的控制器中:

    var sedi = new List<string>();
    sedi.Add("Via Gavinana, 19, Roma");
    sedi.Add("Val de Seine, 94600 Choisy le Roi");
    sedi.Add("Street 21,Shuwaikh, Kuwait");
    var sediString = JsonConvert.SerializeObject(sedi);
    ViewBag.sediList = sediString;
    return View();
    

    在您的视图中隐藏以在 java 脚本中使用它:

    <input type="hidden" id="sediString" name="sediString" value="@ViewBag.sediList">
    

    并在您的 java 脚本中像这样使用它:

    var data = JSON.parse($("#sediString").val());
    

    你可以将你的数据放在数组中,并在每个函数中使用它:

    $.each(data, function (i, item) {
    //enter your code
    }
    

    编辑1: 对于 javascript 不是 jquery 使用:

    var data = JSON.parse(document.getElementById(sediString).val());
    

    而不是

    var data = JSON.parse($("#sediString").val());
    

    并使用 normal 代替 $.each

    for (var i = 0; i < data.length; i++) {
           addMarker(data[i], map);
        }
    

    编辑2:

    您不需要隐藏输入来访问 java 脚本中的视图包。 你可以在javascript中使用它:

    var data = JSON.parse(@ViewBag.sediList);
    

    【讨论】:

    • 你能用“普通”javascript代码而不是jquery重写它吗?
    • 为什么在这里使用隐藏字段?这种方法不应该用在 MVC 中
    • @BorisSokolov 因为我想在我的 javascript 中访问从控制器发送的数据。数据必须在某个地方才能在 javascript 中保存
    • 但它可以访问此示例中的 Model 或 ViewBag。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2015-06-02
    • 2022-10-16
    相关资源
    最近更新 更多