jonatan roufe
jonatan roufe

Reputation: 31

pass client side javascript value to server side C#

I'm trying to pass the value of a variable created in java script in to the server side.

I'm using asp.net AJAX C#.

I was able to insert the value into an asp:Label by using:

document.getelementbyid("MyLabel").innerhtml = "data";

but once i try to get the value in the server side:

string NewLabel = MyLabel.Text;

it shows a null error.

does anyone know a way to pass the java script value to the server?

Thank you.

Upvotes: 2

Views: 9900

Answers (3)

Sutherland Nele
Sutherland Nele

Reputation: 47

You can send the client value to the server side either by posting the data, ajax or passing it as a parameter in a query string. Without doing any of these, I very much doubt that the server would be able to see the values set on the client side.

Upvotes: 0

rahularyansharma
rahularyansharma

Reputation: 10755

take a hidden field and set the variable value on hidden field like this

i assume that Mylable is hidden field

  var javascriptvariable='a';
  $('#MyLabel').val(javascriptvariable);

and on server side

   string NewLabel = MyLabel.Value;

I have used jquery for this /

Upvotes: 0

Jupaol
Jupaol

Reputation: 21365

You should use another control to send the value on each post, for example:

  • HiddenField

  • Any Input control

Example:

ASPX

<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script>
    $(function () {
        $("#<%: this.myHidden.ClientID %>").val("your new value");
    });
</script>

<asp:HiddenField runat="server" ID="myHidden" Value='' />

ASPX Code behind

string myHiddenValue = this.myHidden.Value;

Upvotes: 1

Related Questions