For the following code:
<% foreach (Entities.Core.Location loc in locations){ %> <div class='place_meta'> <img src='~/static/images/stars/star_25_sml.gif' runat='server' class='star_rating'/> </div> <% }; %>
I would like to display the star rating image for each location object displayed. However, only the first location object’s star rating is displayed. For the rest, the image tag becomes <img class='star_rating' />
Am I missing anything in the syntax that allows the ability to have controls with runat=server within a foreach on the aspx page? This is with ASP.net 2.0.
I could possibly call a function in the codebehind or a display class to absolute map the URL but I am very curious if there is a solution to this problem.
Just for clarifications, the path to the image could possibly be different for each location object.
You can’t use server controls within an inline loop, because ASP.NET needs to be able to uniquely identify each control to process it. The for… loop prevents this. The easiest and cleanest way is to use a Repeater control and bind your collection to it (in code-behind). Set the URL property in the bind event handler, and maintain a counter variable while binding, to check if you’re at the first item or not.
Edit: I’ve played around with this some more, and found that if you assign an ID attribute, all looped instances get the same ID, but ASP.NET only recognizes the first control found. This would be an extremely dirty way to set properties on the first instance only. Please don’t write code like this.