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>
<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
</td>
</tr>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Mmm.... have you tried this?
@int i
@foreach(myGroupRecordsDef inedClass 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.
@int i
@foreach(myGroupRecordsDef
@{i++}
<tr>
<td>
<div id="jquery-jplayer-@i" class="cp-jplayer"></div>
</td>
</tr>
}
Razor syntax could be a bit weird sometimes.
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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks!
ASKER
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(myGroupRecordsDef
@i++
<tr>
<td>
<div id="jquery-jplayer-@i" class="cp-jplayer"></div>
</td>
</tr>
}