简体   繁体   中英

How to assign Javascript return value in c# Code behind Variable

How to assign the javascript return value to c# code behind variable, while the page load. I am trying to do this. Please see the below example. I want the exact result like this.

Note : I already posted a question like this,but that is meaning less.

Javascript:
<script>
function GetValue() {
return 10;
}
</script>

C#.NET

protected void Page_Load(object sender, EventArgs e)
{
int Data
ClientScript.RegisterStartupScript(this.GetType(), "GetData", "a=GetValue();alert(a)", true);
Data=a;//a is Javascript Variable
}

What you are asking is impossible. The page load is part of the aspnet webforms request/response lifecycle. This determines what page content is generated.

The JavaScript will run on the client browser, after the page content has been generated. So there is no way to use any server side methods to get your value on page generation.

You can either pass the value as a querystring, post back a value or use a web service.

Take a hidden field or Label in the form. Assign return value to the Hidden form with document.getElementById('ID').value = 10;
Call this function from CodeBehind and get the value of Hiddnefield in the code behind.
I hope this helps.

To be more clear do something like this...

In your HTML define a tag like this

<asp:HiddenField ID="hfData" runat="server" />

And then write a javascript function that looks like this

 function putData()
     {
        document.getElementById('hfData').value = 10;
     }

and then on your page_load do something like this

 protected void Page_Load(object sender, EventArgs e)
   {
     int Data = hfData.Value;
   }

this should get youur client side data on server side for further processing

您可以将JavaScript值存储在隐藏变量中,然后从后面的代码中访问该值。

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