在页面加载时从隐藏字段中抓取JS值

时间:2011-12-13 00:28:14

标签: c# javascript asp.net .net geolocation

我正在尝试在.NET中为uni项目实现一些Google Maps内容。

但是,我正在努力将我的坐标设置为我的.NET Google地图控件。

我认为最简单的方法是使用HTML5地理定位API来获取当前位置的坐标,然后在我的.NET代码中抓取它们并使用它们使地图居中。

我有以下JS代码:

    $(document).ready(function () {
            if (Modernizr.geolocation) {
                navigator.geolocation.getCurrentPosition(getCoords);
            }
            else {
                // no support
            }

            function getCoords(position) {
                $("#lat").val(position.coords.latitude);
                $("#long").val(position.coords.longitude);
            }
    });

这会将纬度和经度的坐标放在各自隐藏的文本框中,#lat#long

现在,我想在代码隐藏的.NET代码中获取它们。我试着这样做:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        // some other code
    }

    // maps
    addStoreMap.enableDragging = false;
    addStoreMap.enableGoogleBar = false;

    // grab the coordinates here.
    decimal lat = Convert.ToDecimal(hdnLat.Value);
    decimal lng = Convert.ToDecimal(hdnLong.Value);
}

但是,这总是返回一个空值。我似乎无法将坐标值加载到我的.NET代码中。当我通过JS提醒他时,我得到了值。这是因为Page_Load事件发生在我的JS被执行之前?如果是这样,我将如何解决这个问题?

由于

1 个答案:

答案 0 :(得分:1)

ready上的document事件没有.preventDefault(),因此该行引发了错误。它从未进入geolocation代码。删除行:

e.preventDefault();

演示:http://jsfiddle.net/ThinkingStiff/mGj2W/

HTML:

<input id="lat" type="hidden" /><input id="long" type="hidden" />
<div id="result"></div>

脚本:

$( document ).ready( function () {

    if ( true ) { //modernizr check here

        navigator.geolocation.getCurrentPosition( getCoords );

    }
    else {

        // no support

    }

    function getCoords( position ) {

        $( '#lat' ).val( position.coords.latitude );
        $( '#long' ).val( position.coords.longitude );

        $( '#result' ).text( $( '#lat' ).val() + ', ' + $( '#long' ).val() );

    }

} );

输出:

39.583129, -124.4872483