MVC 3 Razor View:从布尔模型值生成 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8560531/
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
MVC 3 Razor View: Generating JavaScript from a boolean model value
提问by musefan
I am using ASP.Net MVC 3 Razor view engine.
我正在使用 ASP.Net MVC 3 Razor 视图引擎。
I have a requirement to generate some JavaScript code in my View based on a value in my View Model. The value I need to use is a boolean, for this example lets call it IsSet
.
我需要根据我的视图模型中的值在我的视图中生成一些 JavaScript 代码。我需要使用的值是一个布尔值,在这个例子中我们称之为IsSet
.
So what I want to do is create a JavaScript boolean based on this value that I can use in the script later on.
所以我想要做的是基于这个值创建一个 JavaScript 布尔值,稍后我可以在脚本中使用它。
Keep in mind that for all below examples I have this bit of code at the top of my view...
请记住,对于以下所有示例,我的视图顶部都有这段代码......
@{ string IsSet = Model.IsSet ? "true" : "false"; }
NOTE: All examples below are JavaScript.
注意:下面的所有示例都是 JavaScript。
First attempt...
第一次尝试...
var IsSet = @(IsSet);
... this actually works, the problem is it breaks the auto-formatting(CTRL + E, D) in VS 2010 due to badly formatted JavaScript - as you might expect, and this is not acceptable.
...这确实有效,问题是由于 JavaScript 格式错误,它破坏了VS 2010 中的自动格式化(CTRL + E,D) - 正如您所料,这是不可接受的。
Second attempt...
第二次尝试...
var IsSet = "@(IsSet)";
...I know, JavaScript is clever, it will auto-parse my string when needed. Ooops, forgot it is a string type and anything other than empty evaluates to true.
...我知道,JavaScript 很聪明,它会在需要时自动解析我的字符串。哎呀,忘了它是一个字符串类型,除了空以外的任何东西都评估为真。
Third attempt...
第三次尝试...
var IsSet = Boolean("@(IsSet)");
....surely this will work... nope, convert non-empty string to true again (bad parser!)
....这肯定会起作用...不,再次将非空字符串转换为真(错误的解析器!)
Fourth attempt...
第四次尝试...
var IsSet = "@(IsSet)" === "true";
Finally something that works, but it doesn't look great to me.
终于有一些有用的东西了,但对我来说看起来不太好。
I will use this if need be but ultimately my question is: Is there a better way to handle this kind of situation? Perhaps, the unwanted behaviour in my first attempt is just something that Microsoft may have overlooked?
如果需要,我会使用它,但最终我的问题是:有没有更好的方法来处理这种情况?也许,我第一次尝试时不想要的行为只是微软可能忽略的东西?
If anybody has a nice and tidy fifth attempt for me, that would be good.
如果有人对我进行了漂亮而整洁的第五次尝试,那就太好了。
The important thing for me is that the auto-formatting in VS 2010 does not break
对我来说重要的是 VS 2010 中的自动格式化不会中断
Thanks
谢谢
采纳答案by nnnnnn
Version 1 is the only one of those that I'd vote for even if they all worked, because it's the most human-readable. Unfortunately I don't have VS at home so I can't try it out to see what the auto-formatting issue is, but if at all possible I'd want to ignore the issue and go ahead and use that version given that there's nothing actually wrong with the code - it is just VS that is confused. (Are you saying VS is trying to interpret the whole thing as JS and thus finding it invalid?)
版本 1 是唯一一个我会投票支持的版本,即使它们都有效,因为它是最易读的。不幸的是,我家里没有 VS,所以我无法尝试查看自动格式化问题是什么,但如果可能的话,我想忽略该问题并继续使用该版本,因为有代码实际上没有任何问题 - 只是 VS 感到困惑。(你是说 VS 试图将整个事情解释为 JS 并因此发现它无效?)
But if you want some other options:
但是如果你想要一些其他的选择:
Fifth attempt...
第五次尝试...
@{ string IsSet = Model.IsSet ? "true" : ""; }
var isSet = !!"@(IsSet)";
// OR
var isSet = Boolean("@(IsSet)");
Coerce the string value into a boolean with the old double-not-operator trick - as you already pointed out both "true" and "false" would become true, but this problem goes away if you use "true" and "" (empty string) - so you can use Boolean()
as per your "third attempt".
使用旧的双重非运算符技巧将字符串值强制转换为布尔值 - 正如您已经指出的“真”和“假”都会变为真,但是如果您使用“真”和“”(空),这个问题就会消失string) - 所以你可以Boolean()
根据你的“第三次尝试”使用。
Sixth attempt...
第六次尝试...
@{ string IsSet = Model.IsSet ? "true" : "false"; }
// helper function at the top of your page:
function bool(strVal) {
return strVal === "true";
}
// variable declaration
var isSet = bool("@(IsSet)");
OK, so you end up with a fairly pointless function at the top of your page, but it keeps the actual variable declarations reasonably tidy and if debugging client side you'll see bool("false")
or bool("true")
.
好的,所以您最终在页面顶部得到了一个相当无意义的函数,但它使实际变量声明保持合理整洁,如果调试客户端,您将看到bool("false")
或bool("true")
.
Seventh attempt...
第七次尝试...
I don't like the extra step of creating the server-side string IsSet = Model.IsSet ? "true" : "false";
in advance. I don't know Razor syntax, but can you say something along the lines of:
我不喜欢string IsSet = Model.IsSet ? "true" : "false";
提前创建服务器端的额外步骤。我不知道 Razor 语法,但你能说一下:
var isSet = !!"@(Model.IsSet ? "true" : "")";
// OR, better:
var isSet = !!"@(rzrBool(Model.IsSet))";
// where rzrBool() is a server-side helper function (that you would create)
// which returns "true" or ""
I would expect all of my "attempts" to work, but again I think your "first attempt" is the best option.
我希望我所有的“尝试”都能奏效,但我再次认为你的“第一次尝试”是最好的选择。
回答by user1003221
I just wrestled with the same issue for about an hour. My final solution was equivalent to the following.
我只是与同样的问题搏斗了大约一个小时。我的最终解决方案相当于以下内容。
var IsSet = @(Model.IsSet.ToString().ToLower()); // Inside JavaScript block
This requires no additional code.
这不需要额外的代码。
回答by Darin Dimitrov
None of the versions shown so far (both in the question and answers) is something that I would use. Here's how I would do it:
到目前为止显示的版本(在问题和答案中)都不是我会使用的。这是我将如何做到的:
@model MyViewModel
<script type="text/javascript">
var isSet = @Html.Raw(Json.Encode(Model.IsSet));
// TODO: use the isSet javascript variable here as a standard boolean value
</script>
or if you needed other properties of your view model to be manipulated with javascript you could JSON encode the entire model:
或者,如果您需要使用 javascript 操作视图模型的其他属性,您可以对整个模型进行 JSON 编码:
@model MyViewModel
<script type="text/javascript">
var model = @Html.Raw(Json.Encode(Model));
if (model.IsSet) {
alert(model.FooBar);
}
</script>
回答by SteffenSH
How about:
怎么样:
@Ajax.ToJson(Model.IsSet)
回答by Tim Medora
var isSet = /true/i.test('@Model.IsSet');
- Single line
- Handles the case difference between .Net and JavaScript
- Works with auto-formatting (Visual Studio, and Visual Studio with Resharper)
- Reasonably idiomatic if you are familiar with JavaScript regexes
- Fairly resilient to logic errors; it should do as intended or throw a JavaScript error (or possibly a Razor compilation error).
- 单线
- 处理 .Net 和 JavaScript 之间的大小写差异
- 适用于自动格式化(Visual Studio 和带有 Resharper 的 Visual Studio)
- 如果您熟悉 JavaScript 正则表达式,则相当地道
- 对逻辑错误相当有弹性;它应该按预期执行或抛出 JavaScript 错误(或可能是 Razor 编译错误)。
回答by Extragorey
I know this is an old question, but none of the answers are particularly elegant.
我知道这是一个老问题,但没有一个答案特别优雅。
The simplest solution in these situations is simply to append +0
to your conditional. This implicitly converts the bool to an int, but since the result is 0
or 1
it's immediately converted back again by the if statement. Example:
在这些情况下,最简单的解决方案是简单地附加+0
到您的条件。这隐式地将 bool 转换为 int,但由于结果是0
或者1
它立即被 if 语句再次转换回来。例子:
// The space is optional
if (@IsSet +0) {
// Do stuff
}
Assigning a boolean value to a variable could be achieved as follows:
将布尔值分配给变量可以按如下方式实现:
// Note the double (not triple) equals, which performs type conversion
var isSet = @IsSet+0 == true;
The code works, you get no red squiggly lines, and the Visual Studio formatter is happy.
代码有效,没有红色波浪线,并且 Visual Studio 格式化程序很满意。
回答by Sébastien Richer
Here is what I use, inside a javascript block:
这是我在 javascript 块中使用的内容:
var someValue;
@{ var someValue= "someValue= " + Model.SomeValue+ ";"; }
@someValue
回答by artwl
var isSet= @((bool)Model.IsSet?"true":"false");
回答by Lasse Edsvik
How about:
怎么样:
@Model.IsSet.ToString().ToLower()