1

It's just me or it is really difficult to work with variables in javascript?

My problem is that I want to use some results of my javascript function into a MVC .net Controller, and I just can't!

1.- My JavaScript function runs on a view:

     $(document).ready(function () {
           $('#go').click(function () {
             // test for presence of geolocation
             if (navigator && navigator.geolocation) {
                 navigator.geolocation.getCurrentPosition(geo_success, geo_error);

             } else {
                 // nothing at this moment.

......

   function geo_success(position) {
         printLatLong(position.coords.latitude, position.coords.longitude);
     }

Besides printLatLong function, I want to use the argument position.coord.latitude to send it to a controller through Html.ActionLink like this:

    @Html.ActionLink("Link to Controller", "Action", "Controller", position.coords.latitude)

But I can't use position.coords.latitude since now I'm out of the function. I just want to use that value as an argument in my ActionLink, is that too difficult?? :(

Thanks in advance for any help.

2
  • 5
    You seem confused as to the differences between client-side and server-side code. Commented Sep 5, 2012 at 8:16
  • Not at all, I want to do some operations with the coordinates at server-side, it's just that I obtain them with client-side code. I'm supposed to make calculations client-side too? I don't think so. Commented Sep 5, 2012 at 18:42

1 Answer 1

1

Just do it with html anchor and manipulate the href attribute via jquery.

Script:

function geo_success(position) {
    printLatLong(position.coords.latitude, position.coords.longitude);
    var url = '@Url.Action("Geo", "Home")';
    // grab the anchor and modify the url
    $("#geolink").attr("href", url += "?latitude=" + position.coords.latitude);
}

In your view

<a id="geolink">GeoLink</a>

HomeController.cs

    public ActionResult Geo(int latitude)
    {
        throw new Exception(String.Format("Do something with: {0}", latitude));
    }
Sign up to request clarification or add additional context in comments.

1 Comment

If you want to keep the ActionLink helper, you may add the id like so: @Html.ActionLink("Link to Controller", "Action", "Controller", new { id = "geolink" })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.