无法增加变量

时间:2015-11-24 14:21:23

标签: html razor

我正在进行导航,出于某种原因,我无法增加变量。

   <ul id="menu">
        <li>
            <a href="/" class="drop">Home</a>
            <div class="dropdown_2columns">
                <!-- Begin 2 columns container -->
                <div class="col_2">
                    <h2>Welcome !</h2>
                </div>
            </div><!-- End 2 columns container -->
        </li><!-- End Home Item -->
        @foreach (var mainNode in rootNode.Children())
        {
            int childCount = 1;
            int numChildren = mainNode.Children().Count();
            int num = 0;                              @*<-------------- Num variable*@
            <li>
                <a href="@mainNode.Url" class="drop">@mainNode.Name</a>
                <div id=main-@num class="dropdown_5columns"> @*<----------Using the variable here*@
                    <!-- Begin 2 columns container -->
                    <div class="col_5">
                        <h2>@mainNode.Name</h2>
                    </div>
                    @* note if you want ALL descendants change .Children to .Descendats*@
                    @foreach (var childNode in mainNode.Children())
                    {
                        // if first node or new set of three open the div and ul @: is used to stop razor trying to
                        // "balance" the tags
                        if (childCount == 1 || (double)childCount % 3 == 1)
                        {
                            @:<div class="col_1">
                                @:<ul>
                        }
                        <a href="@childNode.Url">@childNode.Name</a>

                        // close the div and list if this is either a multiple of 3 or the last one
                        if ((double)childCount % 3 == 0 || numChildren == childCount)
                        {
                            @:</ul>
                        @:</div>
                        }
                        childCount++;
                        num++;    @*< -----------Increasing the varable here*@
                    }
                </div>

            </li>
        }
    </ul>
}

问题在于循环后可变量没有增加。即使多次循环,div id也始终为main-0。有谁知道这个的原因?

1 个答案:

答案 0 :(得分:1)

“Num”放在mainNode循环中,所以它总是设置为0.

你必须将num变量移到mainNode循环之外,它应该可以工作: - )