简体   繁体   中英

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.

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;

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 /

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.

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