我有一个带有不可见标签的 ListView 来存储类别 ID。 我想要做的是在单击按钮时将标签文本分配给 cookie 或 session 。 问题是当我尝试在 ListView 之外显示值时,我的 cookie 始终为 null。 这是我的 aspx 代码:
<asp:ListView runat="server" ID="catListView" DataSourceID="CategoriesDataSource" >
<EmptyDataTemplate>No DataFound</EmptyDataTemplate>
<ItemTemplate>
<div class="service" style="margin-bottom:10px;width:230px;">
<h4 style="font-family:Corbel;" ><%#Eval("CatName") %></h4>
<asp:Label runat="server" Visible="false" ID="lblcat"><%#Eval("CatId") %></asp:Label>
<asp:Button runat="server" ID="btnTest" Text="View Items" OnClick="btnTest_Click" />
</div>
</ItemTemplate>
</asp:ListView>
我的 C# 代码:
protected void btnTest_Click(object sender, EventArgs e)
{
Response.Cookies["cat"].Value = "test";
foreach (ListViewItem item in catListView.Items)
{
Label catLabel = (Label)item.FindControl("lblcat");
Response.Cookies["cat"].Value = catLabel.Text.ToString();
}
}
任何帮助将不胜感激。 提前谢谢
山姆
请您参考如下方法:
当您的 Button 单击事件被调用时,听起来您的 ListView 可能没有数据绑定(bind)。
我建议您使用 the ItemCommand event handler .最适合这种处理方式。更新您的 ListView 声明以处理该事件:
<asp:ListView runat="server" ID="catListView" DataSourceID="CategoriesDataSource
OnItemCommand="catListView_ItemCommand" >
注意:不要忘记从按钮中删除“OnClick”事件处理程序
然后像这样编写您的偶数处理程序代码:
protected void catListView_ItemCommand(object sender, ListViewCommandEventArgs e)
{
Label catLabel = (Label)e.Item.FindControl("lblcat");
Session["currentCatLabelText"] = catLabel.Text;
}
这还有一个好处,就是不用遍历所有 ListView 项,而只查看您单击的项。
