2011-07-11 14 views
3

私はMVCにとってまったく新しいものです。私は自分のコントローラにジオロケーションを使用して取得した経度と緯度の値を渡して、その値を使用してデータベースから正しいデータを識別して取得できるようにしています。ここでJavascriptを介してControllerに値を渡す戻り値MVC3を見るRazor

は、このすべてが正常に動作します私のJavascript

function auto_locate() { 


    alert("called from station"); 
    navigator.geolocation.getCurrentPosition(show_map); 



function show_map(position) { 
    var latitude = position.coords.latitude; 
    var longitude = position.coords.longitude; 
    var locstring = latitude.toString() + "." + longitude.toString(); 
    var postData = { latitude: latitude, longtitude: longitude } 
    alert(locstring.toString()); 

} 

} 

です。

私がする必要があるのは、私のコントローラにpostDataまたはlocstringを渡すことです。これは次のようになります:

[HttpGet] 
public ActionResult AutoLocate(string longitude, string latitude) 
{ 
    new MyNameSpace.Areas.Mobile.Models.Geo 
    { 
     Latitude = Convert.ToDouble(latitude), 

     Longitude = Convert.ToDouble(longitude) 

    }; 


// Do some work here to set up my view info then... 
    return View(); 
} 

解決策を見つけることができませんでした。

上記のjavascriptをHTML.ActionLinkから呼び出し、LongitideとLatitudeをマイコンに追加するにはどうすればよいですか?

答えて

5

あなたは、AJAXを使用することができます:postData = { latitude: latitude, longtitude: longitude };

$.ajax({ 
    url: '@Url.Action("AutoLocate")', 
    type: 'GET', 
    data: postData, 
    success: function(result) { 
     // process the results from the controller 
    } 
}); 

を。

それとも、ActionLinkの持っていた場合:

$(function() { 
    $('#locateLink').click(function() { 
     var url = this.href; 
     navigator.geolocation.getCurrentPosition(function(position) { 
      var latitude = position.coords.latitude; 
      var longitude = position.coords.longitude; 
      var postData = { latitude: latitude, longtitude: longitude }; 
      $.ajax({ 
       url: url, 
       type: 'GET', 
       data: postData, 
       success: function(result) { 
        // process the results from the controller action 
       } 
      }); 
     }); 

     // cancel the default redirect from the link by returning false 
     return false; 
    }); 
}); 
+0

ありがとうSlaks魔法のように動作します:

@Html.ActionLink("foo bar", "AutoLocate", null, null, new { id = "locateLink" }) 

を、このようにあなたは、このリンクをAJAXifyことができます。 –

関連する問題