我的数据源有一个Rating
dataItem包含一个0到5的整数。我想按顺序打印星号。
我正试图在Repeater
控件中执行此操作:
<b>Rating:</b>
<% for (int j = 1; j <= DataBinder.Eval(Container.DataItem, "Rating"); j++)
{ %>
<img src="App_Pics/fullstar.png" />
<% }
for (int j = 1; j <= 5 - DataBinder.Eval(Container.DataItem, "Rating"); j++)
{ %>
<img src="App_Pics/emptystar.png" />
<%} %>
The name 'Container' does not exist in the current context
。这很奇怪,因为当我之前使用<%# DataBinder.Eval(Container.DataItem, "Name")%>
一行时,效果很好。aspx
页面中包含循环是否聪明?我觉得这不太方便。我的选择是什么?#
的含义是什么?非常感谢。
答案 0 :(得分:5)
#
表示在data-binding occurs时(即在控件或页面上调用DataBind()
时)要执行的代码。 <%# %>
语法是<%= %>
的数据绑定等效项,所以不幸的是,您不能将循环包装在<%# %>
块中并完成它。
您可以通过实施代码隐藏方法并将评级传递给方法来解决此限制:
<%# GetStars(Convert.ToInt32(DataBinder.Eval(Container.DataItem, "Rating"))) %>
然后将该方法实现为:
protected string GetStars(int rating)
{
string output = string.Empty;
for (int j = 1; j <= rating; j++) output += "<img src=\"App_Pics/fullstar.png\" />";
for (int j = 1; j <= 5 - rating; j++) output += "<img src=\"App_Pics/emptystar.png\" />";
return output;
}
答案 1 :(得分:2)
#表示数据绑定项,这就是为什么你看到你提到的错误;你在它的上下文之外使用DataBinding。
最好的解决方案是将您的星级评估者转换为外部控件(ascx控件)。您可以添加一个名为“Rating”的属性,从数据绑定上下文中指定它,并在星级评估者控件中进行循环。
答案 2 :(得分:1)
第2点,你当然可以做到,你会在教程和内容中找到一些例子。我个人喜欢尝试在代码隐藏中保留尽可能多的代码,但有时它不值得......
答案 3 :(得分:1)
我不建议以这种方式使用循环。当然,有一些方法可以将5个图像放在一起,就像你需要它们一样打开或关闭星星,但另一个想法是简单地创建6个静态图像,打开0到5个星。 0star.jpg,1star.jpg等。然后您的“评级”值可以简单地用于生成适当的文件名。
答案 4 :(得分:0)
我不确定使用Repeater
控件的循环是个好主意。更好的做法是循环DataSource
本身(在代码隐藏中),因此Repeater
只需要一次迭代来呈现HTML。
如果您需要一些复合HTML结构进行显示,我会使用jvenema的解决方案并使用另一个UserControl
进行渲染。
答案 5 :(得分:0)
最好的方法是让我有类似的东西:
codebehind:
protected List<int> Stars = new List<int> { 1, 2, 3, 4, 5 };
protected int RankingStars = 3;
aspx:
<asp:Repeater runat=server ID=C_Rep_StarsFull DataSource=Stars >
<ItemTemplate>
<img src="App_Pics/fullstar.png" runat=server
visible=<%# RankingStars >= (int)Container.DataItem %>/>
</ItemTemplate>
</asp:Repeater>
<asp:Repeater runat=server ID=C_Rep_StarsEmpty DataSource=Stars >
<ItemTemplate>
<img src="App_Pics/emptystar.png" runat=server
visible=<%# RankingStars < (int)Container.DataItem %>/>
</ItemTemplate>
</asp:Repeater>