如何从后面的代码将 bool 传递给 JavaScript 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19863753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:03:45  来源:igfitidea点击:

How to pass a bool to a JavaScript function from code behind?

c#javascriptasp.netwebformsboolean

提问by GLP

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?

但它似乎不能正常工作。谁能告诉我出了什么问题?

回答by Michael Liu

You are passing capitalized 'True'and 'False'as quoted strings, but the JavaScript Boolean literals are lowercase trueand falsewithout quotes. Change it to:

你逝去的资本'True''False'引字符串,但JavaScript的布尔文字都是小写truefalse不带引号。将其更改为:

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"。)