简体   繁体   English

如何在javascript变量中获取变量值后面的C#代码?

[英]How to get C# code behind variable value in javascript variable?

How to get c# code behind variable value in javascript?如何在javascript中获取变量值后面的c#代码? I have declared a variable in page load.我在页面加载中声明了一个变量。 I want that variable value in javascript.我想要 javascript 中的变量值。

Javascript Javascript

在此处输入图片说明

Code C#代码 C#

在此处输入图片说明

Needs to be at the class level.需要在班级水平。 As your code is now, by the time the page is being rendered that variable is long gone out of scope正如您现在的代码一样,在呈现页面时,该变量早已超出范围

public class Whatever{

  public string OrderID { get; set; }

Make it a property too, if your plan is for it to be public as your naming (capital O) implies如果您的计划是像您的命名(大写 O)所暗示的那样将其公开,则也将其设为财产

您可以将其保留在隐藏输入字段中并在 JavaScript 中访问该隐藏字段值。

You cannot interact between client-side and server-side without sending an HTTP request to the server.如果不向服务器发送 HTTP 请求,就无法在客户端和服务器端之间进行交互。

you cannot assign as javascript variable directly to the code-behind.您不能将作为 javascript 变量直接分配给代码隐藏。

what you can do is like你可以做什么就像

create a hidden field variable in the client side as在客户端创建一个隐藏字段变量作为

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

and in the javascript, you can assign some value to the hidden variable as在 javascript 中,您可以为隐藏变量分配一些值作为

<script type="text/javascript">
        var somefunction = function () {
            var hfVariable = document.getElementById('<%= hfVariable.ClientID %>');
            hfVariable.value = 'value';
        }
    </script>

and you can read the hidden field variable in the code behind as你可以在后面的代码中读取隐藏字段变量

string variable = hfVariable.Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM