5
votes

How come the following code works fine...

        <ul class="searchList">
            @if (Model.Count() > 0)
            {
                foreach (var partner in Model)
                {
                    <li>
                        @Html.ActionLink(@partner.Name, "Details", "Partner", new { id = partner.AID }, null)<br />
                        @partner.Street<br />
                        @partner.CityStateZip<br />
                        @if(!string.IsNullOrEmpty(partner.Phone))
                            {
                               @partner.Phone<br />
                            }
                        @(partner.Distance) miles<br />
                    </li>
                }
            }
        </ul>

But this code does not work fine...

            @if (Model.Count() > 0)
            {
                <ul class="searchList">

                        foreach (var partner in Model)
                        {
                            <li>
                                @Html.ActionLink(@partner.Name, "Details", "Partner", new { id = partner.AID }, null)<br />
                                @partner.Street<br />
                                @partner.CityStateZip<br />
                                @if(!string.IsNullOrEmpty(partner.Phone))
                                    {
                                       @partner.Phone<br />
                                    }
                                @(partner.Distance) miles<br />
                            </li>
                        }

                </ul>
             } 

The second error one returns the following error...

Compiler Error Message: CS0103: The name 'partner' does not exist in the current context.

I am finding the code mixing rules of Razor to be difficult to follow. Any link that gives the canonical explanation will be appreciated.

Seth

3

3 Answers

10
votes

You need to prefix the foreach with @:

@foreach (var partner in Model)

The <ul> is setting Razor back in to markup-mode so you need to add the @ to tell it to go back into a code block.

3
votes

In the second example, you need @foreach to transition from markup to code.

In the first example, you don't, since the direct contents of an if block are already code.

2
votes

you should follow this as a reference, you will never face such problems, any more. :)