简体   繁体   中英

C# and HTML Code together in Razor View MVC

I am trying to achieve something like the following with MVC4 Razor Syntax. Here is the Code I am trying to write:

@{
    int counter = 1;
    @foreach (var item in Model)
    {
        @if (counter == 1)
        {
            <div class="section show">
        }
        else
        {
            <div class="section">
        }                                                
        <span>@counter <text> .</text> @Html.DisplayFor(ab => item.Title)</span>
        <div class="section-content">
            @Html.DisplayFor(ab => item.Description)
        </div>    
    </div>
    counter++;
    }
}

The above Code doesn't give any Compilation Error. But it causes Run time error. It says the Closing Tag is missing. Is it somehow possible to make the C# Code and HTML Code work together to achieve the result that I am trying to achieve here?

I am trying to get the C# Code and make them work based on Condition. For example, in the if Statement, if Counter is 1, the first div class will be selected and in rest of the times, the second div class will be selected.

Thanks. (I have updated the Question)

Don't use the if to create the div. Use it to determine the value of the class attribute:

    @{

    int counter = 1;   
    foreach (var item in Model)    
     {      
      result = "section";

         if (counter == 1)                                                
         {
             result = "section show";                                        
         }

     <div class="@result">
         <span>@counter <text> .</text> @Html.DisplayFor(ab => item.Title)</span>
         <div class="section-content">
             @Html.DisplayFor(ab => item.Description)
         </div>
     </div>
     counter++;
     }                                                                                    
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM