C# 如何使用 MVC4 和 Razor 设置 javascript 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14866539/
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
How to set javascript variables using MVC4 with Razor
提问by Filling The Stack is What I DO
Can someone format the code below so that I can set srcript variables with c# code using razor?
有人可以格式化下面的代码,以便我可以使用 razor 用 c# 代码设置 srcript 变量吗?
The below does not work, i've got it that way to make is easy for someone to help.
下面的方法不起作用,我已经这样做了,很容易让别人帮忙。
@{int proID = 123; int nonProID = 456;}
<script type="text/javascript">
@{
<text>
var nonID =@nonProID;
var proID= @proID;
window.nonID = @nonProID;
window.proID=@proID;
</text>
}
</script>
I am getting a design time error
我收到设计时错误
采纳答案by Felipe Oriani
You should take a look at the output that your razor page is resulting. Actually, you need to know what is executed by server-side
and client-side
. Try this:
您应该查看 razor 页面产生的输出。实际上,您需要知道server-side
and执行了什么client-side
。尝试这个:
@{
int proID = 123;
int nonProID = 456;
}
<script>
var nonID = @nonProID;
var proID = @proID;
window.nonID = @nonProID;
window.proID = @proID;
</script>
The output should be like this:
输出应该是这样的:
Depending what version of Visual Studio you are using, it point some highlights in the design-time for views with razor.
根据您使用的 Visual Studio 版本,它指出了带有 razor 的视图在设计时的一些亮点。
回答by Sean
Since razor syntax errors can become problematic while you're working on the view, I totally get why you'd want to avoid them. Here's a couple other options.
由于 razor 语法错误在您处理视图时可能会成为问题,我完全理解您为什么要避免它们。这里有几个其他选项。
<script type="text/javascript">
// @Model.Count is an int
var count = '@Model.Count';
var countInt = parseInt('@Model.ActiveLocsCount');
</script>
The quotes act as delimiters, so the razor parser is happy. But of course your C# int becomes a JS string in the first statement. For purists, the second option might be better.
引号充当分隔符,因此 razor 解析器很高兴。但是当然你的 C# int 在第一条语句中变成了一个 JS 字符串。对于纯粹主义者来说,第二种选择可能更好。
If somebody has a better way of doing this without the razor syntax errors, in particular maintaining the type of the var, I'd love to see it!
如果有人有更好的方法来做到这一点而没有剃刀语法错误,特别是维护 var 的类型,我很乐意看到它!
回答by Rob Church
Not so much an answer as a cautionary tale: this was bugging me as well - and I thought I had a solution by pre-pending a zero and using the @(...)
syntax. i.e your code would have been:
与其说是一个警示故事,不如说是一个答案:这也困扰着我 - 我认为我有一个解决方案,即在前面加一个零并使用@(...)
语法。即你的代码本来是:
var nonID = 0@(nonProID);
var proID = 0@(proID);
Getting output like:
获得输出如:
var nonId = 0123;
What I didn't realise was that this is how JavaScript (version 3) represents octal/base-8 numbers and is actually altering the value. Additionally, if you are using the "use strict";
command then it will break your code entirely as octal numbers have been removed.
我没有意识到这是 JavaScript(第 3 版)表示八进制/基数 8 数字的方式,并且实际上正在改变该值。此外,如果您正在使用该"use strict";
命令,那么它会完全破坏您的代码,因为八进制数已被删除。
I'm still looking for a proper solution to this.
我仍在寻找合适的解决方案。
回答by Scott Gartner
This is how I solved the problem:
我是这样解决问题的:
@{int proID = 123; int nonProID = 456;}
<script type="text/javascript">
var nonID = Number(@nonProID);
var proID = Number(@proID);
</script>
It is self-documenting and it doesn't involve conversion to and from text.
它是自我记录的,不涉及与文本的转换。
Note: be careful to use the Number()
function not create new Number()
objects - as the exactly equals operator may behave in a non-obvious way:
注意:小心使用Number()
函数 not create new Number()
objects - 因为完全等于运算符可能以不明显的方式运行:
var y = new Number(123); // Note incorrect usage of "new"
var x = new Number(123);
alert(y === 123); // displays false
alert(x == y); // displays false
回答by mabian69
It works if you do something like this:
如果您执行以下操作,它会起作用:
var proID = @proID + 0;
Which produces code that is something like:
它产生的代码类似于:
var proID = 4 + 0;
A bit odd for sure, but no more fake syntax errors at least. Sadly the errors are still reported in VS2013, so this hasn't been properly addressed (yet).
肯定有点奇怪,但至少没有更多的假语法错误。遗憾的是,VS2013 中仍然报告了这些错误,因此(尚未)正确解决此问题。
回答by Ryan Young
I've been looking into this approach:
我一直在研究这种方法:
function getServerObject(serverObject) {
if (typeof serverObject === "undefined") {
return null;
}
return serverObject;
}
var itCameFromDotNet = getServerObject(@dotNetObject);
To me this seems to make it safer on the JS side... worst case you end up with a null variable.
对我来说,这似乎使它在 JS 方面更安全......最坏的情况是你最终得到一个空变量。
回答by saluce
I've seen several approaches to working around the bug, and I ran some timing tests to see what works for speed (http://jsfiddle.net/5dwwy/)
我已经看到了几种解决该错误的方法,并且我进行了一些计时测试以查看哪些方法可以提高速度(http://jsfiddle.net/5dwwy/)
Approaches:
方法:
- Direct assignment
In this approach, the razor syntax is directly assigned to the variable. This is what throws the error. As a baseline, the JavaScript speed test simply does a straight assignment of a number to a variable.
- Pass through `Number` constructor
In this approach, we wrap the razor syntax in a call to the `Number` constructor, as in `Number(@ViewBag.Value)`.
- ParseInt
In this approach, the razor syntax is put inside quotes and passed to the `parseInt` function.
- Value-returning function
In this approach, a function is created that simply takes the razor syntax as a parameter and returns it.
- Type-checking function
In this approach, the function performs some basic type checking (looking for null, basically) and returns the value if it isn't null.
- 直接分配
在这种方法中,razor 语法直接分配给变量。这就是引发错误的原因。作为基准,JavaScript 速度测试只是将数字直接分配给变量。
- 通过`Number`构造函数
在这种方法中,我们将 razor 语法包装在对 `Number` 构造函数的调用中,如 `Number(@ViewBag.Value)`。
- 解析整数
在这种方法中,razor 语法被放在引号内并传递给 `parseInt` 函数。
- 返回值函数
在这种方法中,创建的函数只是将 razor 语法作为参数并返回它。
- 类型检查功能
在这种方法中,该函数执行一些基本的类型检查(基本上是查找 null),如果它不为 null,则返回该值。
Procedure:
程序:
Using each approach mentioned above, a for-loop
repeats each function call 10M times, getting the total time for the entire loop. Then, that for-loop is repeated 30 times to obtain an average time per 10M actions. These times were then compared to each other to determine which actions were faster than others.
使用上面提到的每种方法,a 将for-loop
每个函数调用重复 10M 次,从而获得整个循环的总时间。然后,该 for 循环重复 30 次以获得每 10M 操作的平均时间。然后将这些时间相互比较,以确定哪些动作比其他动作更快。
Note that since it is JavaScript running, the actual numbers other people receive will differ, but the importance is not in the actual number, but how the numbers compare to the other numbers.
请注意,由于它是 JavaScript 运行的,其他人收到的实际数字会有所不同,但重要的不是实际数字,而是这些数字与其他数字的比较。
Results:
结果:
Using the Direct assignment approach, the average time to process 10M assignments was 98.033ms. Using the Number
constructor yielded 1554.93ms per 10M. Similarly, the parseInt
method took 1404.27ms. The two function calls took 97.5ms for the simple function and 101.4ms for the more complex function.
使用直接分配方法,处理 10M 分配的平均时间为 98.033 毫秒。使用Number
构造函数每 10M 产生 1554.93ms。同样,该parseInt
方法花费了 1404.27 毫秒。简单函数的两次函数调用耗时 97.5 毫秒,更复杂的函数调用耗时 101.4 毫秒。
Conclusions:
结论:
The cleanest code to understand is the Direct assignment. However, because of the bug in Visual Studio, this reports an error and could cause issues with Intellisense and give a vague sense of being wrong.
最容易理解的代码是直接赋值。但是,由于 Visual Studio 中的错误,这会报告错误并可能导致 Intellisense 出现问题并给出模糊的错误感。
The fastest code was the simple function call, but only by a slim margin. Since I didn't do further analysis, I do not know if this difference has a statistical significance. The type-checking function was also very fast, only slightly slower than a direct assignment, and includes the possibility that the variable may be null. It's not really practical, though, because even the basic function will return undefined if the parameter is undefined (null in razor syntax).
最快的代码是简单的函数调用,但幅度很小。由于我没有做进一步的分析,我不知道这个差异是否有统计学意义。类型检查函数也非常快,仅比直接赋值稍慢,并且包括变量可能为空的可能性。但是,这并不实用,因为如果参数未定义(剃刀语法中的 null),即使是基本函数也会返回 undefined 。
Parsing the razor value as an int and running it through the constructor were extremely slow, on the order of 15x slower than a direct assignment. Most likely the Number
constructor is actually internally calling parseInt
, which would explain why it takes longer than a simple parseInt
. However, they do have the advantage of being more meaningful, without requiring an externally-defined (ie somewhere else in the file or application) function to execute, with the Number
constructor actually minimizing the visible casting of an integer to a string.
将 razor 值解析为 int 并通过构造函数运行它非常慢,比直接赋值慢 15 倍。很可能Number
构造函数实际上是在内部调用parseInt
,这可以解释为什么它比简单的parseInt
. 然而,它们确实具有更有意义的优点,不需要执行外部定义的(即文件或应用程序中的其他地方)函数,Number
构造函数实际上最小化了整数到字符串的可见转换。
Bottom line, these numbers were generated running through 10M iterations. On a single item, the speed is incalculably small. For most, simply running it through the Number
constructor might be the most readable code, despite being the slowest.
最重要的是,这些数字是通过 1000 万次迭代生成的。在单个项目上,速度小得无法估量。对于大多数人来说,简单地通过Number
构造函数运行它可能是最易读的代码,尽管它是最慢的。
回答by Ahmed Ghazey
@{
int proID = 123;
int nonProID = 456;
}
<script>
var nonID = '@nonProID';
var proID = '@proID';
window.nonID = '@nonProID';
window.proID = '@proID';
</script>
回答by RAM
I use a very simple function
to solve syntax errors in body of JavaScript
codes that mixed with Razor
codes ;)
我使用一个非常简单的方法function
来解决JavaScript
与Razor
代码混合的代码体中的语法错误;)
function n(num){return num;}
var nonID = n(@nonProID);
var proID= n(@proID);
回答by Arsman Ahmad
One of the easy way is:
一种简单的方法是:
<input type="hidden" id="SaleDateValue" value="@ViewBag.SaleDate" />
<input type="hidden" id="VoidItem" value="@Model.SecurityControl["VoidItem"].ToString()" />
And then get the value in javascript:
然后在javascript中获取值:
var SaleDate = document.getElementById('SaleDateValue').value;
var Item = document.getElementById('VoidItem').value;