首页 > 解决方案 > 如何使用 ASP.NET 获取数据属性?

问题描述

我似乎找不到与我遇到的问题相关的任何内容。

目标

我正在尝试从单击按钮时在代码隐藏中创建的按钮(Web 控件)获取自定义数据属性的值。我正在引用MSDN-Attribute.GetCustomAttribute 方法,但我不确定这是否适合我正在尝试做的事情。

我当前的点击子在下方,但不起作用。

默认.ascx

<asp:UpdatePanel ID="itemWrapper" UpdateMode="Conditional" runat="server">
  <ContentTemplate>
    <asp:PlaceHolder ID="itemsPlaceholder" runat="server" />
  </ContentTemplate>
</asp:UpdatePanel>

Default.ascx.vb(代码隐藏)

Protected Sub Items_Load()
  Dim dynamicID = "13"
  Dim itemBtn = New Button()
      itemBtn.Attributes.Add("data-custom-id", dynamicID) '<- Custom attribute I want to get
      itemBtn.UseSubmitBehavior = False
      itemBtn.Text = "select"
      itemBtn.ID = "Button_" & dynamicID
      AddHandler itemBtn.Click, AddressOf ItemSelectBtn_Click
      itemsPlaceholder.Controls.Add(itemBtn) 
End Sub

Public Sub ItemSelectBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
  Dim clickedBtn = DirectCast(sender, Button),
      clickedBtnID As String = clickedBtn.Attributes("data-custom-id")

      Console.WriteLine("this button's ID is " & clickedBtnID)
End Sub

HTML 输出

<div id="Content_C001_itemWrapper">
  <input type="button" 
   name="ctl00$Content$C001$1"
   value="select"
   onclick="target = '_blank';__doPostBack('ctl00$Content$C001$1','')"
   data-custom-id="13">
</div>

更新

这是最简单的答案。不知道为什么这不起作用,但正如@zgood 建议的那样获取属性。VB.NET 使用Attributes("attribute-name")Attributes["attribute-name"]不像在 C# 中。仅供参考。

谢谢您的帮助!

标签: asp.netvb.net

解决方案


推荐阅读