在Razor视图中有条件地更改CSS类

dri*_*ght 19 css c# razor asp.net-mvc-3

我需要<div>使用'forumChild'类更改标记的CSS 类.它必须改变foreach循环的每3个循环.

有没有办法在控件内执行此操作?

<div class="Forum">
    <p>The Forum</p>

            @foreach (var item in Model)
            {               
                <div class="ForumChild">

                    <img src="@item.Blog.Image.img_path" alt="Not Found" />

                    <br />
                            @foreach (var comment in item.Blog.comment)
                            {

                                var db = new ACapture.Models.ACaptureDB();

                                var Name = from p in db.Profile.AsEnumerable()
                                           where (p.AccountID == comment.AccountID)
                                           select p;                            
                            <section>
                                    <div>
                                        <a href="@Url.Action("Index", "Home")">@foreach (var y in Name)
                                                                              { @(y.FirstName + " " + y.LastName + ":");
                                                                              }</a>
                                    </div>
                                    <div>
                                        @comment.Commentation 
                                    </div>
                            </section>
                            }
                </div>                
            }
</div>
Run Code Online (Sandbox Code Playgroud)

提前致谢

Shy*_*yju 50

 @{
   int counter=0;
 }
 @foreach (var item in Model)
 { 
   counter++;
   <div class="@(counter<=3 ? "classRed":"classBlue")">
       <img src="@item.Blog.Image.img_path" alt="Not Found" />
       //other markup also here

   </div>  
    if (counter == 6)
    {
        counter = 0;
    }

 }
Run Code Online (Sandbox Code Playgroud)

classRedclassBlue是CSS类


use*_*301 5

我们如何处理这个问题:

1)您需要创建帮助方法,该方法将通过一些代码返回 css 类。

string GetDivClass(int code)
{
  var classes = new [] {"first", "second", "third"};
  return classes[code];
}
Run Code Online (Sandbox Code Playgroud)

2)创建计数器/索引并每次在循环中递增。

3) 像GetDivClass(index % 3)div元素一样调用辅助方法。

聚苯乙烯

它只是POC,所以不要在真正的应用程序中使用它(您需要添加验证逻辑并将“类”初始化移动到另一个地方)。

  • 对于您的示例,最好在函数内部进行模运算。这样,调用者就不需要知道它有多少项,而且您将来还可以在不破坏现有代码的情况下添加更多项。 (3认同)