How to pass values from ViewBag to a Javascript function in an ASP.NET MVC application

0

I have the following ActionResult Controller in my application. In this ActionResult I have two ViewBags that capture a deserialization of Longitude and Latitude values originating from a Google API.

The values arrive perfectly in the ViewBag below coming like this -21.1234567 and -51.1234567

    ViewBag.Latitude = Double.Parse(a1, CultureInfo.InvariantCulture);
    ViewBag.Longitude = Double.Parse(a2, CultureInfo.InvariantCulture);

Code below ActionResult

public ActionResult Detalhes(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    Empresa empresa = db.Empresa.Find(id);

    if (empresa == null)
    {
        return HttpNotFound();
    }

    WebClient client = new WebClient();

    string url = "https://maps.googleapis.com/maps/api/geocode/json?address=[Numero]+[Endereco],+[Bairro],+[Estado]&key=MINHA CHAVE";

    url = url.Replace("[Numero]", empresa.Numero);
    url = url.Replace("[Endereco]", empresa.Endereco.Replace(" ", "+"));
    url = url.Replace("[Bairro]", empresa.Bairro.Replace(" ", "+"));
    url = url.Replace("[Estado]", empresa.Estado);

    string value = client.DownloadString(url);

    dynamic dyn = JsonConvert.DeserializeObject(value);

    string a1 = dyn["results"][0].geometry.location.lat;

    string a2 = dyn["results"][0].geometry.location.lng;

    /* QUERO PASSAR OS VALORES ABAIXO PARA A VIEW */
    ViewBag.Latitude = Double.Parse(a1, CultureInfo.InvariantCulture);
    ViewBag.Longitude = Double.Parse(a2, CultureInfo.InvariantCulture);

    return View(empresa);
}

Below in the View I have the following script that I got in the API section of Google Script variables are not getting values

        var a1 = @(ViewBag.Latitude);
        var a2 = @(ViewBag.Longitude);

Part of the View for Google Maps

<h3>Localização</h3>
<div id="map"></div>
<script>
    function initMap() {

        var a1 = @(ViewBag.Latitude);
        var a2 = @(ViewBag.Longitude);

        var uluru = { lat: a1, lng: a2 };
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 17,
            center: uluru,
            gestureHandling: 'cooperative'
        });
        var marker = new google.maps.Marker({
            position: uluru,
            map: map
        });
    }
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MINHACHAVE&callback=initMap">
</script>
    
asked by anonymous 10.11.2017 / 21:52

1 answer

0

Hello, good evening.

As I see your logic is correct, the only item that causes you to not be able to carry data (decimals, in this case) between Controller and JavaScript, is that the decimal placeholder in your application is different. It is probably "," (comma), so when serializing the value, JavaScript does not understand this as a valid separator because it uses the "." Separator. (dot).

For correction, it is necessary to change settings in the culture of your application.

As the example:

//Recupera o nome da cultura que está sendo utilizada pela aplicação
string strCulturaAtual = Thread.CurrentThread.CurrentCulture.Name;
//Cria um novo objeto que poderá personalizar configurações de sua cultura
//Como neste caso, que usaremos para casas decimais, mas neste, 
//também é possível configurar informações de formato de data por exemplo.
CultureInfo cultureInfo = new CultureInfo(strCulturaAtual);
//Novo separador de casas decimais
cultureInfo.NumberFormat.NumberDecimalSeparator = ".";
//Altera a cultura atual, pela nova que criamos.
Thread.CurrentThread.CurrentCulture = cultureInfo;

Soon after this configuration, you will fill in the ViewBag (I set the values, to be explicit our goal), as the example:

ViewBag.Latitude = -21.1234567;
ViewBag.Longitude = -51.1234567;

And in JavaScript, you can retrieve the value normally:

<script type="text/javascript">
    var latitude = @ViewBag.Latitude;
    var longitude = @ViewBag.Longitude;
</script>

So I think you can solve your problem.

    
11.11.2017 / 01:22