@if (Model.Count() > 0) {...">

How to include ul tags inside razor code block?

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 is not working 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 returns the following error ...

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

I find the Razor code mixing rules difficult to follow. Any reference giving a canonical explanation would be appreciated.

Set

+5
source share
3 answers

You need a prefix foreachwith @:

@foreach (var partner in Model)

<ul>sets Razor back to pegging mode, so you need to add @to tell it to return to the code block.

+10
source

@foreach .

, if .

+3

you should follow this as a reference, you will never encounter such problems again. :)

+2
source

All Articles