如何在ASP.NET Repeater中获取点击项的食谱名称?
解决方案
1. 修改Repeater中的链接,传递食谱名称参数
直接在<a>标签的href属性里拼接查询参数,把当前项的recipeName传过去即可。为避免特殊字符(如空格、中文)导致传递异常,记得用Server.UrlEncode对参数值编码:
<asp:Repeater ID="RepeaterR" runat="server"> <ItemTemplate> <table> <a href='ViewRecipe.aspx?recipeName=<%# Server.UrlEncode(Eval("recipeName").ToString()) %>'> <div class="property-image"> <div class="property-image-title"> </div> </div></a> <div class="property-description"> <h5><%# Eval("recipeName")%></h5> <p><%#Eval("avgRating") %> stars</p> <asp:Image class="img" runat="server" src=<%#Eval("recipePic") %> /> </div> <a href='ViewRecipe.aspx?recipeName=<%# Server.UrlEncode(Eval("recipeName").ToString()) %>'> <div class="property-social-icons"> </div> </a> </table> </ItemTemplate> </asp:Repeater>
2. 在ViewRecipe.aspx中接收并展示食谱名称
在ViewRecipe.aspx的后台代码(如ViewRecipe.aspx.cs)里,通过Request.QueryString获取传递的参数,再绑定到页面的展示控件上:
后台代码示例:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string recipeName = Request.QueryString["recipeName"]; if (!string.IsNullOrEmpty(recipeName)) { // 假设页面有一个ID为lblRecipeName的Label控件用于展示 lblRecipeName.Text = recipeName; } } }
前台展示控件示例(ViewRecipe.aspx中):
<h3>当前查看食谱:<asp:Label ID="lblRecipeName" runat="server" /></h3>
补充提示
如果你的食谱有唯一标识ID(如recipeId),更推荐传递ID而非名称——ID不会有特殊字符,还能避免重名问题,之后在ViewRecipe.aspx中通过ID从数据库查询完整食谱信息即可。
内容的提问来源于stack exchange,提问作者KK2007
相关产品推荐
相关产品推荐

