简体   繁体   中英

foreach in ASP.net with nested runat=“server”

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.

Unless you're using MVC, you might find a Repeater Control more useful in this situation.

If I remember correctly, you can use a source of data (your locations in this instance) and then loop through and set each image.

I don't know if your code is supposed to work, but this one is ;-)

<asp:Image ImageUrl="~/static/images/stars/star_25_sml.gif" runat="server" class="star_rating" />

Perhaps it's what you are looking for.

EDIT: looking at the code of System.Web.UI.HtmlControls.HtmlImage you can see that the src attribute is removed after the (first) processing. This may be the reason why you can get just the first URI correct with your code.

I would remove the runat="server" attribute and reference the image using a relative path (or the full path) instead of using the tilde.

EDIT: FWIW, @miies idea fits the ASP.NET paradigm AND is an example of why I'm switching to ASP.NET MVC.

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