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 ">
6
  • possible duplicate of How to pass JavaScript variables to PHP? Commented Jul 23, 2015 at 0:08
  • @TinyGiant: I am not using php. Instead it's asp.net. thnks Commented Jul 23, 2015 at 0: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. Commented Jul 23, 2015 at 0: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. Commented Jul 23, 2015 at 0:14
  • Then you should clarify that in your question. Commented Jul 23, 2015 at 0:15

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.