How to pass Viewbag values to a Javascript Function in an ASP.NET MVC application

Asked

Viewed 4,041 times

1

I have the following Actionresult Controller in my application. In this Actionresult I have two Viewbag that captures a Longitude and Latitude values from a Google API.

The values arrive perfectly in the Viewbag below so coming -21.1234567 and -51.1234567

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

Code below the 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 View I have the following script I picked up in the API section of Google Script variables are not taking values

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

Part of the View referring to 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=MINHA CHAVE&callback=initMap">
</script>

1 answer

1

Hello, good night.

From what I see your logic is correct, the only item that makes you not able to carry data (decimals, in this case) between Controller and Javascript, is that the decimal separator of your application is different. It’s probably "," (comma), so when serializing the value, Javascript doesn’t understand it as a valid separator, because it uses the "separator." (point).

For correction, you need to change settings in the culture of your application.

As follows 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 setting, you will fill in the Viewbag (I set the values, to make our goal explicit), as the example:

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

And in Javascript, you can recover the value normally:

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

With that, I think you can solve your problem.

  • 2

    Amigo @Wesley Ferreira I was able to solve in this way var latitude = @Html.Raw(Json.Encode(@Viewbag.Latitude)) and so the variable picks the value with point, and thus passing to Google Maps the corresponding values correctly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.