简体   繁体   English

MVC 3 Razor View:从布尔模型值生成JavaScript

[英]MVC 3 Razor View: Generating JavaScript from a boolean model value

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. 我需要根据View Model中的值在View中生成一些JavaScript代码。 The value I need to use is a boolean, for this example lets call it IsSet . 我需要使用的值是布尔值,对于此示例,我们将其称为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. ...我知道,JavaScript很聪明,它会在需要时自动解析我的字符串。 Ooops, forgot it is a string type and anything other than empty evaluates to true. 哎呀,忘了它是一个字符串类型,除了空之外的任何东西都评估为true。

Third attempt ... 第三次尝试 ......

var IsSet = Boolean("@(IsSet)");

....surely this will work... nope, convert non-empty string to true again (bad parser!) ....肯定这会工作...不,再次将非空字符串转换为true(糟糕的解析器!)

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 谢谢

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. 这不需要额外的代码。

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>

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. 版本1是我投票的唯一一个,即使它们都有效,因为它是最人性化的。 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. 不幸的是我家里没有VS所以我无法尝试看看自动格式化问题是什么,但如果可能的话我想忽略这个问题并继续使用那个版本,因为那里有代码没有什么问题 - 只是VS很困惑。 (Are you saying VS is trying to interpret the whole thing as JS and thus finding it invalid?) (你是说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". 使用旧的双非运算符技巧将字符串值强制转换为布尔值 - 正如您已经指出的那样,“true”和“false”都将成为现实,但如果使用“true”和“”(空,则此问题会消失) 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"; 我不喜欢创建服务器端string IsSet = Model.IsSet ? "true" : "false";的额外步骤string IsSet = Model.IsSet ? "true" : "false"; string IsSet = Model.IsSet ? "true" : "false"; in advance. 提前。 I don't know Razor syntax, but can you say something along the lines of: 我不知道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. 我希望我的所有“尝试”都有效,但我认为你的“第一次尝试”是最好的选择。

怎么样:

@Ajax.ToJson(Model.IsSet)
var isSet = /true/i.test('@Model.IsSet');
  • Single line 单线
  • Handles the case difference between .Net and JavaScript 处理.Net和JavaScript之间的区别
  • Works with auto-formatting (Visual Studio, and Visual Studio with Resharper) 使用自动格式化(Visual Studio和带有Resharper的Visual Studio)
  • Reasonably idiomatic if you are familiar with JavaScript regexes 如果您熟悉JavaScript正则表达式,则合理惯用
  • Fairly resilient to logic errors; 对逻辑错误具有相当的弹性; it should do as intended or throw a JavaScript error (or possibly a Razor compilation error). 它应该按预期执行或抛出JavaScript错误(或可能是Razor编译错误)。

Here is what I use, inside a javascript block: 这是我在javascript块中使用的内容:

var someValue;
@{ var someValue= "someValue= " + Model.SomeValue+ ";"; }
@someValue

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. 在这些情况下最简单的解决方案就是将+0附加到条件。 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. 这会隐式地将bool转换为int,但由于结果为01因此if语句会立即将其转换回来。 Example: 例:

// 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格式化程序很高兴。

怎么样:

@Model.IsSet.ToString().ToLower()
var isSet= @((bool)Model.IsSet?"true":"false");

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

相关问题 在MVC Razor中的Javascript中,使用模型中的值替换关键字 - In Javascript in a MVC Razor, replace a keyword with a value from the model 使用MVC Razor语法检查Java中的视图模型属性是否具有值 - Check if view model property has value in Javascript using MVC Razor syntax 从javascript函数调用mvc razor视图 - call mvc razor view from javascript function 如何从IEnumerable返回带有索引的模型 <model> 在MVC剃刀视图中? - how to return model with index from IEnumerable<model> in mvc razor view? 如何在MVC的Razor视图中更新Model值并重新加载div - How to update the Model value and reload a div in Razor view in MVC 如何使用 Razor 从 ASP.net MVC 视图中 JavaScript 内的资源文件中获取值 - How to fetch value from resource file inside JavaScript in ASP.net MVC view using Razor 将模型和其他参数从View传递到Controller Razor MVC3 - Passing Model and extra parameters from View to Controller Razor MVC3 混合Razor和Javascript:在视图中为Model分配一个数字给Javascript变量 - Mixing Razor and Javascript: Assigning a number from Model to a Javascript variable in a view Javascript未在MVC Razor视图中运行 - Javascript not running in MVC Razor view 如何在Razor视图中更新JavaScript中的模型值? - How do I update a model value in JavaScript in a Razor view?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM