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 an image with a rated star for each location displayable. However, only the first star rating of the location object is displayed. Otherwise, the image tag becomes<img class="star_rating" />

Am I missing anything in the syntax that allows you to have controls with runat = server inside foreach in an aspx page? This is from ASP.net 2.0.

I could call a function in codebehind or a display class for an absolute url map, but I'm very curious if there is a solution to this problem.

For illustrative purposes only, the path to the image may be different for each location object.

+1


source to share


4 answers


You cannot use server controls inside an inline loop, because ASP.NET must be able to uniquely identify each control in order to handle it. The for ... loop prevents this from happening. The easiest and cleanest way is to use the Repeater control and bind your collection to it (in code). Set the url property in your binding event handler and store the spinner variable when binding to check if you are in the first element or not.



Edit: I played around with this a bit more and found that if you assign the ID attribute, all instances with the loop get the same ID, but ASP.NET only recognizes the first control it finds. This would be an extremely messy way of setting properties for the first instance only. Please don't write code like this.

+3


source


If you are not using MVC, you can find Repeater Control in this situation.



If I remember correctly, you can use the datasource (your locations in this instance) and then loop through and set each image.

+1


source


I don't know if your code should work, but this one :-)

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

      

Perhaps this is what you are looking for.

EDIT: Look at the code System.Web.UI.HtmlControls.HtmlImage

, you can see the attribute src

is removed after the (first) processing. This may be the reason why you can only get the first URI with your code.

+1


source


I would remove the attribute runat="server"

and link to the image using a relative path (or full path) instead of using a tilde.

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

0


source







All Articles