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.
@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.
Best Answer
Or you can use the
@:
syntax instead of the<text>
element in your loop. Here is a tutorial.