简体   繁体   中英

Set value of asp:HiddenField in Client side and Get that value in Server side

I'm having trouble with setting value of asp:HiddenField in aspx webpage and getting that value in C# code behind.

HTML brief code

<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# brief code

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

I'm having 2 asp:HiddenField and a asp:Button. When OnClientClick is called, showData() will call getData() and of course, run other functions. getData() will call getMarkerData() in Code behind. The thing is, I couldn't get HiddenField's value from the code behind. Rather than that, everything works fine.

Please, give me some advise as I'm newbie in web coding

Thank all

Code behind:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM