Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将C#变量传递给JS的最佳方法_C#_Javascript - Fatal编程技术网

将C#变量传递给JS的最佳方法

将C#变量传递给JS的最佳方法,c#,javascript,C#,Javascript,我有几个用JS编写的函数,可以在我的站点上执行错误检查。在一个实例上,如果DB中的某个实例为true,我想禁用其中两个检查 我在aspx.cs上有类似的东西 if (this.exemptcheck == true) { // could set a variable to pass or whatever is optimal here } 然后在JS中,我在我的.aspx中有这样一个函数 if (NotANumberCheck(item.GetMember("TotalSpace").

我有几个用JS编写的函数,可以在我的站点上执行错误检查。在一个实例上,如果DB中的某个实例为true,我想禁用其中两个检查

我在aspx.cs上有类似的东西

if (this.exemptcheck == true) {
  // could set a variable to pass or whatever is optimal here
}
然后在JS中,我在我的.aspx中有这样一个函数

if (NotANumberCheck(item.GetMember("TotalSpace").Value, 'Space must be Numeric') == false) { return false; }
如果this.exampltcheck返回true,我不希望运行此检查。这样做的最佳方式是什么?我听说过将变量放在不可见的字段中,但这似乎并不理想。如有任何建议,将不胜感激


感谢您,您可以在页面中编写一个脚本部分,将变量设置为true/false,然后稍后在JS中检查该变量。

在aspx中,设置一个名为ExemptCheck的成员变量。稍后,在JS中,执行以下操作:

var exemptCheck = <% Response.Write(ExemptCheck.ToString()) %>;
var-exemptCheck=;

这将为您提供一个与C#变量值相同的JS变量。

您可以响应。仅当This.examptcheck为true时,才编写()javascript代码。

只需注册JS函数,如果条件为true,则无需检查变量:

C#代码:


最后,我使用以下命令设置aspx.cs代码中的值


Page.ClientScript.RegisterStartupScript(this.GetType(),“”,var stackedUnknownExemptCheck=true;“,true)

旁注:通常不鼓励显式检查布尔值是否等于true或false。布尔值已经是布尔值。至少在C#和JS中,这应该不是一个问题这给了我以下错误编译器错误消息:CS0103:当前上下文中不存在名称“ExcemptCheck”?这是范围问题还是我做错了什么?这是范围问题。ExcemptCheck需要是整个页面对象的成员变量,而不仅仅是pageSetup函数;之间的代码在页面呈现函数期间执行,在页面设置函数退出很久之后执行。
if (this.exemptcheck == true) {
    Page.ClientScript.RegisterStartupScript(Page.GetType(), "KEY", "/* code of your JS function that handle the true case */", true);
}