Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSHTML use C# variable in element ID

Lets say I have a for-loop to generate elements in a table:

@for (var i = 0; i < Model.Count(); i+=2) {
  <tr>
    @{var a = Model.ElementAt(i); var b = Model.ElementAtOrDefault(i + 1);}
    <td>
      <div id="r@i" class="rack-container">
        ...              
      </div>
      <div id="s@i" class="rack-selector fade">
        ...                   
      </div>
    </td>
    <td>
      @if (b != null) {
        <div id="r@i+1" class="rack-container">
          ...              
        </div>
        <div id="s@i+1" class="rack-selector fade">
          ...                   
        </div>
      }
    </td>
  </tr>
}

The problem is that the element is literally assigned "r@i" instead of "r1","r2"..."rN" and so on. Is there any way to combine text and a variable as an element ID?

like image 750
nlowe Avatar asked Nov 15 '13 21:11

nlowe


People also ask

What is Cshtml CS file?

cshtml extension is a C# HTML file that is used at server side by Razor Markup engine to render the webpage files to user's browser. This server side coding is similar to the standard ASP.NET page enabling dynamic web content creation on the fly as the webpage is written to the browser.

What does in Cshtml do?

"The @ character starts inline expressions, single statement blocks, and multi-statement blocks:" - from asp.net/web-pages/tutorials/basics/…

Is Cshtml the same as Razor?

All Razor files end with . cshtml. Most Razor files are intended to be browsable and contain a mixture of client-side and server-side code, which, when processed, results in HTML being sent to the browser.


1 Answers

Try:

<div id="s@(i + 1)" class="rack-selector fade">

It might be worth having a quick read of this.

like image 99
John H Avatar answered Oct 20 '22 19:10

John H