剃刀语法和Javascript [英] Razor Syntax and Javascript
问题描述
作为测试我转换,我们已经从Web窗体剃刀书面证明的概念应用程序,只需所以我们可以对其进行评估。
As a test I'm converting a proof-of-concept app we've written from Web Forms to Razor, simply so we can evaluate it.
我碰到的一个问题,到目前为止这是使我的头hurt..generating客户端Javascript ...
I've run into one problem so far that's making my head hurt..generating client-side Javascript...
<script type="text/javascript">
var jqGridIdList = "<%: Url.Action ("getidlist", "office", new { area = "reports" }) %>";
var availableIds = [];
<% for (var i = 0; i < Model.Data.Count (); i++) { %>
availableIds.push({ value : "<%: Model.Data.ElementAt (i).Text %>", label : "<%: Model.Data.ElementAt (i).Text %>" });
<% } %>
</script>
剃刀语法
<script type="text/javascript">
var jqGridIdList = "@Url.Action("getidlist", "office", new { area = "reports" })";
var availableIds = [];
@for(var i = 0; i < Model.Data.Count (); i++) {
availableIds.push({ value : "@Model.Data.ElementAt(i).Text", label : "@Model.Data.ElementAt(i).Text" });
}
</script>
编译器给我下面的错误上的availableIds.push'行:
The compiler gives me the following error on the 'availableIds.push' line:
编译器错误信息:CS1525:无效的前pression术语{
Compiler Error Message: CS1525: Invalid expression term '{'
这显然试图编译为C#...但我怎么阻止它?
It's obviously trying to compile it as C#...but how do I stop it?
谢谢,
基隆
Thanks,
Kieron
推荐答案
您需要敷在伪元素&LT;文字和GT;
。这将切换解析器回HTML模式,然后它会解析JavaScript作为HTML而不是C#的一部分。它发生的原因是 @for()
是内处理一个C#块什么也被认为是C#,直到它是由一个HTML标签逃过一劫。既然你可能不希望一个HTML标签剃须刀提供了&LT;文本方式&gt;
标签来切换模式
You need to wrap it in the pseudo element <text>
. This will switch the parser back to html mode and it will then parse the javascript as part of the html and not c#. The reason it happens is the @for()
is a c# block and anything treated within is also considered c# until it's escaped by an html tag. Since you probably don't want an html tag razor provides the <text>
tag to switch modes.
如果你发现在你的asp.net web表单的差异会终止&LT;%为
与行%&GT;
这需要它的C#模式。如果你下载的Visual Studio 2010剃刀荧光笔扩展它会帮助你看到当code作为code和HTML视为HTML进行处理。
If you notice the difference in your asp.net webforms you end the <% for
line with a %>
which takes it out of c# mode. If you download the razor highlighter extension for visual studio 2010 it will help you see when code is treated as code and html is treated as html.
<script type="text/javascript">
var jqGridIdList = "@Url.Action("getidlist", "office", new { area = "reports" })";
var availableIds = [];
@for(var i = 0; i < Model.Data.Count (); i++) {
<text>availableIds.push({ value : "@Model.Data.ElementAt(i).Text", label : "@Model.Data.ElementAt(i).Text" });</text>
}
</script>
更新最新版本
您现在可以使用 @
语法更易读
<script type="text/javascript">
var jqGridIdList = "@Url.Action("getidlist", "office", new { area = "reports" })";
var availableIds = [];
@for(var i = 0; i < Model.Data.Count (); i++) {
@:availableIds.push({ value : "@Model.Data.ElementAt(i).Text", label : "@Model.Data.ElementAt(i).Text" });
}
</script>
这篇关于剃刀语法和Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!