无法访问后面的代码隐藏字段值

时间:2014-09-26 11:44:35

标签: javascript c# asp.net

javascript:
<script type="text/javascript">
    var map;
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();

    $(document).ready(function () {

        //draw a map centered at Empire State Building Newyork
        var latlng = new google.maps.LatLng(28.536360, 77.398130);
        var myOptions = {
            zoom: 15,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        directionsDisplay = new google.maps.DirectionsRenderer();
        directionsDisplay.setMap(map);
        //directionsDisplay.setPanel(document.getElementById("divDirections"));

        $("#btnGetDirections").click(function () {
            calcRoute($("#txt_schooladdress").val(), $("#txt_address").val());

            //alert("Hello Testing");
        });


    });
    function displayDirections(result) {
        var html = '<div style="margin:5px;padding:5px;background-color:#EBF2FC;border-left: 1px solid #EBEFF9;border-right: 1px solid #EBEFF9;text-align:right;">';
        html = html + '<span><strong>' + $.trim(result.routes[0].legs[0].distance.text.replace(/"/g, '')) + ', ' + $.trim(result.routes[0].legs[0].duration.text.replace(/"/g, '')) + '</strong></span></div>';
        document.getElementById('<%= distance.ClientID %>').value = $.trim(result.routes[0].legs[0].distance.text.replace(/"/g, ''));
        alert(document.getElementById("<%= distance.ClientID %>").value);
        alert(lblBrand.value);
        $("#divDirections").html(html);
</script>


 aspx code:

  <asp:HiddenField ID="distance" runat="server" ClientIDMode="Static"/>


 code behind:

  protected void btn_submit_click(object sender, EventArgs e)
  {
     string distancecla = Request.Form[distance.Value];
  }

我正在设置从java脚本到隐藏字段的值但是无法在点击按钮时获取值我可以看到隐藏字段值的警报但是它没有显示在页面后面的代码上,在页面后面的代码上我得到空值。 ...尝试了很多不同的过程,但仍然没有价值......请帮助我...真的很感谢你......需要一个严格的答案。

2 个答案:

答案 0 :(得分:1)

它是服务器端控件,因为它有 runat =“server”属性:

<asp:HiddenField ID="distance" runat="server" ClientIDMode="Static"/>

您可以使用其ID来访问它,因为它是服务器端控件:

string distancecla = distance.value;

如果您想从Request对象进行访问,请为其添加名称属性:

<asp:HiddenField ID="distance" name="distance" runat="server" ClientIDMode="Static"/>

并在代码背后:

string distancecla = Request.Form["distance"];

答案 1 :(得分:1)

如果您想使用Request.Form["distance"],请使用标准HTML输入代码,并确保为其添加name属性:

<input type="hidden" id="distance" name="distance" value="initialValue" />

如果您正在使用asp控件,那么您可以

protected void btn_submit_click(object sender, EventArgs e)
{
    string distancecla = distance.Value;
}