ekkis
ekkis

Reputation: 10236

'x' is a 'variable' but is used like a 'method'

I'm struggling with a curious situation. I have a collection of pages that I mean to iterate through in Razor. I need to do it twice, once within a script tag and once outside. now, I understand that Razor is meant to generate HTML and not Javascript but this was working fine and now it's breaking and I can't figure out quite why. here's the code that breaks:

<script type="text/javascript">
    @foreach (string page in pages)
    {
        <text>
        function @page() {
            // something here
        }
        </text>
    }
</script>

this works fine:

<div class="intro">
    @foreach (string page in pages)
    {
        <div id="@page">
            <!-- whatever -->
        </div>
    }
</div>

Compiler Error Message: CS0118: 'page' is a 'variable' but is used like a 'method'

and it points to the use of @page. in fact VS13 also red-squiggles the use of the variable but only in the first case!

what's going on here?

Upvotes: 1

Views: 259

Answers (2)

ekkis
ekkis

Reputation: 10236

ha! I figured it out. it needs a bloody space, or some kind of expression terminator:

<text>
function @page () {

(notice the space after @page, which indicates to Razor the expression has ended), or:

<text>
function @(page)() {

of course, the IDE still whines about expecting an identifier (the function name), but that's because it's not meant to generate Javascript

Upvotes: 1

chsword
chsword

Reputation: 2062

try

<script type="text/javascript">
@foreach (string page in pages)
{
    <text>
    function @(page)() {
        // something here
    }
    </text>
}

Upvotes: 1

Related Questions