我得到了一个绑定到转发器的用户控件列表。
用户控件:(示例)“AppProduct”
<div>
<asp:Button ID="btn_details" runat="server" Text="Trigger" />
<asp:HiddenField ID="pid" runat="server" value="5"/>
</div>
转发器:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<App:Product ID="P1" runat="server" />
</ItemTemplate>
</asp:Repeater>
问题:
当我在某个用户控件上按某个“btn_details”时,我需要调用javascript或Jquery函数 根据“pid”的值执行某些操作,但这些是服务器端ID 如何为我点击的用户控件获取这些控件的ClientID。
答案 0 :(得分:2)
.NET 4.0 set
ClientIDMode = "Static"
对于较旧的.NET使用
'<%= Control.ClientID %>'
对于你的情况
function Get_Product_Details(uc) {
var hidden_pid = uc.getElementById('<%= pid.ClientID %>');
}
答案 1 :(得分:1)
我找到了解决这个问题的方法
首先我设置转发器ClientIDMode:
<asp:Repeater ID="Repeater1" runat="server" ClientIDMode="Predictable">
<ItemTemplate>
<App:Product ID="prd1" runat="server" />
</ItemTemplate>
</asp:Repeater>
其次我在clientClick
上为btn_details添加了一个函数 <asp:Button ID="btn_details" runat="server" Text="פרטים נוספים" OnClientClick="Get_Product_Details(this);" />
在该函数中,我提取按钮的客户端ID并解析隐藏字段pid的客户端ID
<asp:HiddenField ID="pid" runat="server" Value="5"/>
将提取客户端ID的函数// ContentPlaceHolder1_Repeater1_Prd_2_pid_2:
function Get_Product_Details(btn) {
//ContentPlaceHolder1_Repeater1_Prd_2_btn_details_2
var s = btn.id;
var start = s.indexOf("btn_details");
var end = s.lastIndexOf("_");
sub = s.substring(start, end);
s = s.replace(sub, "pid");
var hidden = document.getElementById(s);
var id = hidden.value;
答案 2 :(得分:0)
由于转发器可以包含您控件的多个实例,因此它会在ID上附加一个数字以唯一标识它。使用jQuery查找相对于按钮的其他元素。 .siblings()应该做到这一点。
答案 3 :(得分:0)
而不是使用隐藏元素作为按钮上的pid,您可以通过jquery .data附加值:
private StringBuilder builder;
public void Page_Load(object sender, EventArgs e)
{
Repeater1.ItemDataBound += generateData;
Repeater1.DataBound += outputGeneratedData;
if (!Postback)
{
List<Product> products = new List<Product>();
// generate our data to bind
Repeater1.DataSource = products;
Repeater1.DataBind();
}
}
// it is possible to do this inside the user control as well on page_load which would simplify it.
public void generateData(objectSender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// presumes your custom control is the first control in the repeater.. if not you can use FindControl to get the relevent controly
MyUserControl ctl = (MyUserControl)e.item.Controls[0];
// you could expose the buttons id in a property on the control but if prefered just use FindControl.
builder.AppendFormat("$('{0}').data('PID','{1}');", ctl.FindControl('btn_details').ClientID ,((Product)e.item.DataItem).ProductID);
}
}
public void outputGeneratedData(object sender,Eventargs e)
{
Response.Write(@"<script type='text/javascript'> + builder.ToString() + "</script>");
}
通过客户端js项目对此进行访问:
function Get_Product_Details(item)
{
var productId = $(item).data('ProductID');
}