ASP.NET 转发器控件 - 获取转发器控件内的隐藏字段值



我在中继器控件中有一个隐藏字段,在中继器控件外部有一个按钮。 下面是我拥有的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 个中继器,每个中继器将具有不同的类别 ID。我在每个中继器中都有一个名为"添加"的链接按钮,当我按下该按钮时,我将打开一个模式弹出窗口,它将有一个按钮。单击该按钮时,我需要显示相应的 CategoryID,该 CategoryID 属于我在其中单击"添加链接"按钮的中继器控件。

但是,隐藏字段 hf 显示为空,我无法获得该手风琴的隐藏字段的值.

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

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 LinkButton。

<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 及其值,并将该值分配给一个新的隐藏字段,并将该值检索到我的单击事件中。

最新更新