Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include ul tags inside of a 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 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

like image 454
Seth Spearman Avatar asked May 06 '12 19:05

Seth Spearman


1 Answers

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.

like image 182
pjumble Avatar answered Sep 30 '22 19:09

pjumble