在客户端设置asp:HiddenField的值,在服务器端获取该值

时间:2016-06-16 10:51:24

标签: c# asp.net hiddenfield

我在aspx网页中设置asp:HiddenField的值并在C#代码中获取该值时遇到了麻烦。

HTML简要代码

<head>
  <script type="text/javascript">
    function getData() {
      markerData = [ <%= getMarkerData() %> ];
    }

    function showData() {
      ...
      getData();
      ...
    }
  </script>
</head>

<body>
  <form id="form1" runat="server">
    <asp:hiddenfield id="hfvarFrom" runat="server" />
    <asp:hiddenfield id="hfvarTo" runat="server" />
    <div class="panel panel-primary" id="divInformation" style="width: 300px;">
      <div class="panel-body" style="height: 650px;">
        <div class="form-group">
          <asp:button id="btnLoadData" runat="server" class="btn btn-warning btn-block" text="LOAD DATA" onclientclick="javascript:showData(); return false;" usesubmitbehavior="false" />
        </div>
      </div>
    </div>
  </form>
  <script>
    $(document).ready(function() {
      $('#<% =btnLoadData.ClientID %>').click(function(e) {
        $('#<% =hfvarFrom.ClientID %>').attr('value', '2016-06-14');
        $('#<% =hfvarFrom.ClientID %>').attr('value', '2016-06-14');
      });
    });
  </script>
</body>

C#简要代码

protected String getMarkerData()
{
    String from = hfvarFrom.Value;
    String to = hfvarTo.Value;
    return getMarkerObjects(from, to);
}

我有2个asp:HiddenField和一个asp:Button。调用OnClientClick时,showData()将调用getData(),当然还会运行其他函数。 getData()将在Code中调用getMarkerData()。 问题是,我无法从后面的代码中获取HiddenField的值。而不是那样,一切正常。

请给我一些建议,因为我是网络编码的新手

全部谢谢

1 个答案:

答案 0 :(得分:2)

代码背后:

protected void Page_Load(object sender, EventArgs e)
{
}

protected void btnOK_Click(object sender, EventArgs e)
{
    string from = hfvarFrom.Value;
    string to = hfvarTo.Value;
}

<强> .ASPX:

<head runat="server">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#<%=hfvarFrom.ClientID %>').val("2016-06-14");
            $('#<%=hfvarTo.ClientID %>').val("2016-06-15");
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:HiddenField ID="hfvarFrom" runat="server" />
        <asp:HiddenField ID="hfvarTo" runat="server" />
        <asp:Button ID="btnOK" runat="server" Text="OK" OnClick="btnOK_Click" style="height: 29px; width: 37px" />
    </form>
</body>