Conditionally change CSS class in Razor view

前端 未结 4 924
别那么骄傲
别那么骄傲 2020-11-30 09:31

I need to change the CSS class of the

tag with the \'forumChild\' class. It has to change every 3 loops of the foreach loop.

Is there a way

相关标签:
4条回答
  • 2020-11-30 10:14

    How we handle this issue:

    1) you need to create helper method that will return css class by some code.

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

    2) create counter/index and increment it in the loop each time.

    3) invoke helper method like GetDivClass(index % 3) at the div element.

    PS

    It is only POC, so don't use it in a real application (you need to add a validation logic and move 'classes' initialization to another place).

    0 讨论(0)
  • 2020-11-30 10:18

    You can add a counter variable to will start with 1 and increment in loop. Check with if statement is true by % and change the class name

    @{ int counter = 1;}
    
     @foreach (var item in Model)
    {
    
    if( (counter % 3) ==0 )
    {
     <div class="ChangedName">
    }
    else
    {
     <div class="ForumChild">
    }
    i++;
    
    0 讨论(0)
  • 2020-11-30 10:19
     @{
       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;
        }
    
     }
    

    Where classRed and classBlue are the CSS classes

    0 讨论(0)
  • 2020-11-30 10:25

    You can write any code you like into a Razor view, so to do what you're thinking of, you could do something like this (I left out most of the inner stuff):

    @{
        var className = "ForumChild";
    }
    <div>
        @for (int i = 0; i < Model.Count; i++)
        {
            var item = Model[i];
            if (i % 3 == 0)
                className = GetNewClassName(); // Or whatever
            <div class="@className">
            </div>
        }
    </div>
    
    0 讨论(0)
提交回复
热议问题