2

I am trying to write javascript variable(hdnField) to server side. In javascript code I have assigned the value of "HiddenField" Control and then I want to write this value to server side. Here's my Client side script:

<script type="text/javascript">
  var hdnField = document.getElementById('<%= hdnField.ClientID%>');                        
  hdnField.value = 100; 
</script>

Server side:

<form action="#" runat="server">
  <div class="left"><%Response.Write(hdnField.Value);%></div>
  <asp:hiddenfield id="hdnField" runat="server" ></asp:hiddenfield>
</form>

I viewed the Page src and was able to retrieve the "hdnField" which is :

<input id="hdnField" type="hidden" name="hdnField" value="100 ">
smtp
  • 159
  • 2
  • 4
  • 11
  • possible duplicate of [How to pass JavaScript variables to PHP?](http://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php) –  Jul 23 '15 at 00:08
  • @TinyGiant: I am not using php. Instead it's asp.net. thnks – smtp Jul 23 '15 at 00:10
  • 1
    I realized that may not be the best duplicate, but the concept is the same. You cannot access a client-side variable from the server-side, you have to send that data to the server manually, best bet is AJAX. –  Jul 23 '15 at 00:12
  • @TinyGiant: Yes, it's possible to do that with ajax. I think you can do that using hiddenfield. That's what i am trying to achieve here. – smtp Jul 23 '15 at 00:14
  • Then you should clarify that in your question. –  Jul 23 '15 at 00:15
  • I think your question is more about receiving post data, thus the pass/send implication of your question may be misleading those who know asp better from helping. Please consider if http://stackoverflow.com/questions/976613/get-post-data-in-c-asp-net is the answer, or helps your improve your question. – Cris Mooney Jul 23 '15 at 00:24

1 Answers1

0

I don't know where

  <div class="left"><%Response.Write(hdnField.Value);%></div>

Comes into play because that looks more ASP than ASP.NET web forms, but if you have:

<asp:hiddenfield id="hdnField" runat="server" ></asp:hiddenfield>

You can read and write to this on the client via:

document.getElementById('<%= hdnField.ClientID %>').value = 'XYZ';

alert(document.getElementById('<%= hdnField.ClientID %>').value);

On the server, you can read and write to this via:

hdnField.Text = "XYZ";

var text = hdnField.Text;

As long as hdnField is not in a template or list control, you can refer to it directly on the server, with the <asp:HiddenField> control you can do both. This bridges the gap so that you can change the value on the client, then retrieve the value on postback. AJAX is only necessary if you need to send the value to the server before the next postback occurs, or out of the normal flow of the ASP.NET postback lifecycle.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257