简体   繁体   English

Javascript从后面的c#代码中读取公共变量

[英]Javascript read public variable from c# code behind

Trying to use public properties from C# code behind and want to read the variable value from a JavaScript function尝试使用 C# 代码中的公共属性并希望从 JavaScript 函数读取变量值

JavaScript function: JavaScript 函数:

function IsAgentInProgram()
{
    var optStatus = "<%=AgentOptInStatus%>";

    if (optStatus == "True")
        alert("You are opted in!");
    else
        alert ("You are opted OUT");
}

C# code behind后面的 C# 代码

public bool AgentOptInStatus;

private void Page_Load(object sender, System.EventArgs e)
{
    this.AgentOptInStatus = true;

}

This does not work.这不起作用。 Output comes back as You are opted OUT .You are opted OUT输出返回。 I also did an alert on optStatus and it comes back with: "<%=AgentOptInStatus%>"我还对optStatus了警报,它返回: "<%=AgentOptInStatus%>"

Am I missing something?我错过了什么吗?

You cannot read the client side variables directly in the codebehind.您不能直接在代码隐藏中读取客户端变量。 What you can do is creating a hidden field and setting the value with javascript, then you can read it in c#.您可以做的是创建一个隐藏字段并使用javascript设置值,然后您可以在c#中读取它。

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

JS: JS:

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

c# : C# :

string selected = hdnfldVariable.Value.ToString();

Another option is to make an HTTP request to the server to call a function from a controller passing the data as parameters.另一种选择是向服务器发出 HTTP 请求,以从将数据作为参数传递的控制器调用函数。

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

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