Link to home
Start Free TrialLog in
Avatar of JT_SIRO
JT_SIRO

asked on

How to create dynamic IDs from loop in MVC 3

I have a loop of records, and I want to create a div with unique ID for each record.  I want the div name to be appended with the ID of the record.  For example:

<div id="jquery_jplayer_1"  class="cp-jplayer"></div>
<div id="jquery_jplayer_2"  class="cp-jplayer"></div>
<div id="jquery_jplayer_3"  class="cp-jplayer"></div>

I'm new to MVC.  My code here is rendering literally, not as the ID value.  Please advise:


                @foreach (var result in group)
                {                                
                <tr>
                    <td>
                        <div id="jquery_jplayer_@result.ID"  class="cp-jplayer"></div>
                    </td>
                 </tr>
ASKER CERTIFIED SOLUTION
Avatar of Bardobrave
Bardobrave
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of JT_SIRO
JT_SIRO

ASKER

Ah, that's a little MVC quirk that I didn't know about.  Thanks!

I also changed the var type to my models type.

One more quick question that should be simple, yet I'm unable to figure out.  I simply want to create a counter within my foreach, so I can use the loop count to dynamically create the div id, instead of using result.ID.  How do I simply create an int variable and increment it?  I can't seem to get the syntax to build without error.  I've tried this:  

@int i
@foreach(myGroupRecordsDefinedClass result in group) {
@i++
    <tr>
      <td>
        <div id="jquery-jplayer-@i"  class="cp-jplayer"></div>
      </td>
    </tr>
}
Mmm.... have you tried this?

@int i
@foreach(myGroupRecordsDefinedClass result in group) {
@{i++}
    <tr>
      <td>
        <div id="jquery-jplayer-@i"  class="cp-jplayer"></div>
      </td>
    </tr>
}

Razor syntax could be a bit weird sometimes.
Avatar of JT_SIRO

ASKER

Even @int i    Causes an error: Invalid expression term 'int'

Shouldn't that work?  I think I'm going to go buy a book on Razor / MVC3, because even this simple stuff isn't working...  hmmmm.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of JT_SIRO

ASKER

Thanks!