C# Javascript 块内的 ASP MVC Razor foreach
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12686014/
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
ASP MVC Razor foreach inside Javascript block
提问by MooCow
I have a Partial View that returns a Javascript function call after I submit an Ajax form. It takes a list of addresses and call Javascript functions to geocode and place markers on a Google Map. When I compile the following code, I get "Conditional compilation is turned off" error around var in the ForEach line.
我有一个局部视图,它在我提交 Ajax 表单后返回一个 Javascript 函数调用。它需要一个地址列表并调用 Javascript 函数来对 Google 地图进行地理编码和放置标记。当我编译以下代码时,在 ForEach 行中的 var 周围出现“条件编译已关闭”错误。
@model IEnumerable<TestStore.Models.Address>
@if (Model.Count() > 0)
{
<script type="text/javascript">
deleteMarkers();
@foreach(var item in Model)
{
codeAddress('@item.GetAddress');
}
</script>
}
I fiddle around with the code and the following does work without compile errors:
我摆弄代码,以下确实没有编译错误:
@if (Model.Count() > 0)
{
<script type="text/javascript">
deleteMarkers();
</script>
foreach (var item in Model)
{
<script type="text/javascript">
codeAddress('@item.GetAddress');
</script>
}
}
For sake of discussion, if I have longer logic that make a lot of Javascript function calls inside loops, I would much prefer to surround everything inside 1 script block. I searched around Stack Overflow and it seem that Razor syntax could go inside a script block but I don't know how that look like in my example.
为了便于讨论,如果我有更长的逻辑在循环内进行大量 Javascript 函数调用,我更愿意将所有内容都包含在 1 个脚本块中。我搜索了 Stack Overflow,似乎 Razor 语法可以进入脚本块,但我不知道在我的示例中它是什么样子。
回答by Darko Z
its because the javascript inside your for loop looks like C# code to Razor. Wrap it in <text>. In general any block content { /* this is block content */ }should always have a single html node - or if you dont need an html node (like in your case) you can use <text>
这是因为 for 循环中的 javascript 看起来像 Razor 的 C# 代码。把它包起来<text>。通常,任何块内容{ /* this is block content */ }都应始终具有单个 html 节点 - 或者如果您不需要 html 节点(如您的情况),则可以使用<text>
@foreach(var item in Model)
{
<text>codeAddress('@item.GetAddress');</text>
}

