简体   繁体   English

如何通过后面的代码将布尔值传递给JavaScript函数?

[英]How to pass a bool to a JavaScript function from code behind?

I have a JavaScript function as follows: 我有一个JavaScript函数,如下所示:

function A(bNeed)
{
    if (bNeed){
        ...
    }
    else{
        ...
    }
}

In my code behind, in Page_Load , I have 在后面的代码中,在Page_Load ,我有

bool bNeed = File.Exists(...);
btn.Attributes.Add("onclick", string.Format("return A('{0}');", bNeed));

But it doesn't seem to work correctly. 但是它似乎无法正常工作。 Can anyone tell me what is wrong? 谁能告诉我这是怎么回事?

You are passing capitalized 'True' and 'False' as quoted strings, but the JavaScript Boolean literals are lowercase true and false without quotes. 您将大写的'True''False'作为带引号的字符串传递,但是JavaScript布尔文字为小写的truefalse不带引号)。 Change it to: 更改为:

btn.Attributes.Add("onclick", string.Format("return A({0});", bNeed ? "true" : "false");

(If you prefer, you could write bNeed.ToString().ToLowerInvariant() instead of bNeed ? "true" : "false" because Boolean.ToString() returns "True" and "False" .) (如果愿意,您可以编写bNeed.ToString().ToLowerInvariant()而不是bNeed ? "true" : "false"因为Boolean.ToString()返回"True""False" 。)

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

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