Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I'm using google api to show a map. In my controller I wrote the following c# code:

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);

In my view:

@{
    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);
        }
    });
  }

And I want show three markers on map corresponding to the location written in the list vb But address has System.Collections.Generic.List1[System.String] value and not the real value of the address. How can I pass the list as parameter to the GetLatLon function in Javascript? How can I fix?

EDIT

I need to show three marker on the map, foreach address. I write:

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
    });
}

Is it possible something like this? How can I fix?

share|improve this question
    
return View(ViewBag.sediList); - looks a bit strange. If you are using ViewBag and there is no model on View - you need return View(). If there is a model, containing the sediList - then you don't need a ViewBag. Just pass the data through the model – Boris Sokolov yesterday
    
GetLatLon("@vb", function(location) - and here you pass string, but not an array – Boris Sokolov yesterday
    
You need to assign it to a javascript variable - var vn = '@Html.Raw(Json.Encode(ViewBag.sediList))'; which will be an array of your 3 address strings. But change your code to delete ViewBag.sediList = sedi; and use return View(sedi); and in the view add @model List<string> then use '@Html.Raw(Json.Encode(Model))'; – Stephen Muecke yesterday
    
@StephenMuecke what reference do I need to add in my project.json to use Encode method? – FabioBit yesterday
1  
@FabioBit, For mvc core, refer this answer – Stephen Muecke yesterday
up vote 0 down vote accepted

So you could create:

Model

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

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

Controller

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);
   }
}

View

@model WebApplication1.Models.MapsModel

...

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

...

And you don't need ViewBag for such cases.

share|improve this answer
    
How can I change GetLatLon('@Html.Raw(Json.Encode(Model.Maps))', function (location) { using @Json.Serialize(...) for aspnet core? – FabioBit yesterday
    
You could try to use some 3rd-parties like '@Newtonsoft.Json.JsonConvert.SerializeObject(Model.Maps)' – Boris Sokolov yesterday
    
I had tried it but it give me the same issue: it pass the string [&quot;Via Gavinana, 19, Busto Arsizio, VA&quot;,&quot;Val de Seine, 94600 Choisy le Roi&quot;,&quot;Street 21,Shuwaikh, Kuwait&quot;] and not the array object. – FabioBit yesterday
    
because it returns string, but not HtmlString. There should be kind of HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(Model‌​.Maps))... JsonHelper.Serialize should solve this issue as well. It should be a part of Asp.net core v5 – Boris Sokolov yesterday
    
Can I use HtmlString like a cast in this way? – FabioBit yesterday

You are not following the best approach but you can use this quick solution.

Controller:=>

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();

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);
        }
    });
  }
share|improve this answer

you must use it something like this: in your controller:

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();

in your view put a hidden for using it in java script:

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

and in your java script use it like this:

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

and you can have your data in array and use it in javascript each function:

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

Edit1: for javascript not jquery use:

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

instead of

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

and use normal for instead of $.each

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

Edit2:

you don't need hidden input for accessing view bag in java script. you can use it in javascript:

var data = JSON.parse(@ViewBag.sediList);
share|improve this answer
    
Can you rewrite it using "normal" javascript code and not jquery please? – FabioBit yesterday
    
Why do you use hidden fields here? This approach is not smth that should be used in MVC – Boris Sokolov yesterday
    
@BorisSokolov because i want to have access to data that send from controller in my javascript. the data must be somewhere to have it in javascript – Abbas Dehghan yesterday
    
But it has access to Model or ViewBag in this sample. – Boris Sokolov yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.