15

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.

2 Answers 2

49

Or you can use the @: syntax instead of the <text> element in your loop. Here is a tutorial.

@:codeAddress(@item.GetAddress);
Sign up to request clarification or add additional context in comments.

1 Comment

even after so long is still very useful
23

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>

@foreach(var item in Model)
{
    <text>codeAddress('@item.GetAddress');</text>
}  

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.