ASP.NET Repeater 控件 - 获取 Repeater 控件内的 Hiddenfield 值

ASP.NET Repeater Control - Getting Hiddenfield value inside the repeater control

我在转发器控件内有一个隐藏域,在转发器控件外有一个按钮。下面是我拥有的asp.code。

<asp:Repeater ID="rptAccordian" runat="server" OnItemDataBound="rptAccordian_ItemDataBound">
  <ItemTemplate>
    <div class="s_panel">
      <h1>
          <a href="#" data-content="Tool tip"><%# Eval("Name") %></a>
      </h1>
      <div>
        <p>
          <small><span style="font-family: 'Segoe UI'; font-weight: bold;">Category Objective: </span><span style="font-family: 'Segoe UI'"><%# Eval("Objective") %></span></small>
        </p>
        <p>
          <small><span style="font-family: 'Segoe UI'; font-weight: bold;">Category Riskscore: </span>
              <code><%# Eval("Score") %><span>%</span></code></small>
        </p>
        <p>
          <code>
               <img src="Content/img/add.png" /><asp:LinkButton ID="Add" runat="server">Add Question</asp:LinkButton>
          </code>
        </p>
        <asp:HiddenField ID="hdnCategoryID" runat="server" Value='<%# Bind("CategoryID") %>' />
      </div>
  </ItemTemplate>
</asp:Repeater>
<div id="modalpopup">
  <asp:Button ID="btnInsertQuestion" runat="server" Text="Save" OnClick="btnInsertQuestion_Click" />
</div>

我的后台代码如下

protected void btnInsertQuestion_Click(object sender, EventArgs e)
{
    HiddenField hf = (HiddenField)rptAccordian.FindControl("hdnCategoryID");
    catID = Convert.ToInt16(hf.Value);
    Response.Write("ID is") + catID;
}

共有13个转发器,每个转发器都有不同的CategoryID。我在每个中继器内都有一个名为 Add 的 Link 按钮,当我按下该按钮时,我将打开一个模式弹出窗口,它会有一个按钮。单击该按钮时,我需要显示属于我单击 ADD link 按钮的转发器控件的相应 CategoryID。

但是,hiddenfield hf 显示为 null,我无法获得该手风琴的 hiddenfield 的值。

您必须获得中继器项目才能访问隐藏字段:

protected void btnInsertQuestion_Click(object sender, EventArgs e)
        {  
            for (int i = 0; i < rptAccordian.Items.Count; i++)
            {
                var item = rptAccordian.Items[i];

                var hf = item.FindControl("hdnCategoryID") as HiddenField;
                var val = hf.Value;
            }
        }   

已更新

protected void Add_Click(object sender, EventArgs e)
        {
            var lb = sender as LinkButton;
            var par = lb.Parent.FindControl("hdnCategoryID");

        }

您无需使用 hiddenfield 即可获得。您需要像这样在中继器中声明 Add LinkBut​​ton。

<asp:LinkButton ID="Add" runat="server" CommandArgument = '<%# Bind("CategoryID")'%> OnClick = "Add_Click">Add Question</asp:LinkButton>

您已经为 btnInsertQuestion 按钮点击编写了代码,而您要求在添加按钮点击中获得 CategoryID,所以我假设您的要求是正确的,但您输入了其他内容。

点击添加按钮获取CategoryId,需要这样写

protected void Add_Click(object sender, EventArgs e)
{
    //Get the reference of the clicked button.
    LinkButton button = (sender as LinkButton );

    //Get the command argument
    string cat_id = button.CommandArgument;
    // Type cast to int if application and use it.
}

我已经使用 jQuery 获得了我的答案。我使用 jQuery 找到了控件 hdnCategoryID 及其值,并将该值分配给一个新的隐藏字段并将该值检索到我的点击事件中。