尝试将布尔 C# 变量传递给 javascript 变量并将其设置为 true
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/656715/
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
Trying to pass in a boolean C# variable to a javascript variable and set it to true
提问by mrblah
Having issues where in my .aspx page I pass in a boolean variable (C#) to a javascript function that is expecting a boolean type.
在我的 .aspx 页面中,我将布尔变量 (C#) 传递给需要布尔类型的 javascript 函数时遇到问题。
BUt the C# variable returns True, and javascript doesn't like the uppercase.
但是 C# 变量返回 True,而 javascript 不喜欢大写。
myjavascript( <%= MyBooleanVariableInCSharp %> );
If I convert the c# variable to string, then my javascript variable becomes a string and not a js bool value!
如果我将 c# 变量转换为字符串,那么我的 javascript 变量将成为字符串而不是 js bool 值!
what is the solution to this nightmare? lol
解决这个噩梦的方法是什么?哈哈
采纳答案by Andrew Hare
Try this:
尝试这个:
myjavascript( <%= MyBooleanVariableInCSharp.ToString().ToLower() %> );
回答by mendel
if you need to do this often, just add this to the top of the javascript (or your js library file, etc.)
如果您需要经常这样做,只需将其添加到 javascript(或您的 js 库文件等)的顶部即可
var True = true, False = false;
Then you code
然后你编码
myjavascript( <%= MyBooleanVariableInCSharp %> );
Would work just fine.
会工作得很好。
Another option if for whatever reason you don't want to use the variables is to write your javascript call like this:
如果出于某种原因不想使用这些变量,另一种选择是像这样编写 javascript 调用:
myjavascript( '<%= MyBooleanVariableInCSharp %>'=='True' );
回答by Chris Hawkes
You could also do this.
你也可以这样做。
myjavascript(<%=myBooleanVariableInCSharp ? "true" : "false" %>);
回答by mireigi
C# has a built-in method for it. At least in .NET v4 and newer.
C# 有一个内置的方法。至少在 .NET v4 和更新版本中。
var myBoolean = <%= myBooleanFromCodeBehind.ToJs() %>;
var myBoolean = <%= myBooleanFromCodeBehind.ToJs() %>;
回答by Hakan F?st?k
The other answers are targeting the old version, before Razor
if you are using Razorthen this is the solution
其他答案针对旧版本,在Razor之前,
如果您使用Razor,那么这就是解决方案
myjavascript( @MyBooleanVariableInCSharp.ToString().ToLower() );
回答by Péter Tajti
function toBool(s){
return s==="True";
}
var b = toBool("@csharpvariable.ToBoolean()");