pass client side javascript value to server side C#

二次信任 提交于 2019-12-13 16:16:32

问题


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.


回答1:


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;



回答2:


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 /




回答3:


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.



来源:https://stackoverflow.com/questions/11600766/pass-client-side-javascript-value-to-server-side-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!