如何获取用户控件下拉列表的ClientID

How to acquire the ClientID of User Control Drop Down List

我创建了一个包含下拉列表的用户控件。我无法获取 ClientID 以获取选定的值或文本。

实施

<%@ Register Src="~/Common/Controls/ReasonPicker.ascx"
TagName="ReasonPicker" TagPrefix="uc2" %>

<td>
<uc2:ReasonPicker ID="ReasonPicker" Width="100%" AutoPostBack="false"
runat="server" AddAny="True" />
</td>

ascx 文件

<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="ReasonPicker.ascx.cs"
Inherits="********.********.com.web.Common.Controls.ReasonPicker" %>

<div runat="server" id="Reasons">
<asp:DropDownList runat="server" AutoPostBack="true" Width="158"
ID="ReasonPickerDropDown"OnSelectedIndexChanged="
ReasonPickerDropDown_SelectedIndexChanged"
onchange="ChangeVisibility(this)">
</asp:DropDownList>
</div>
</div>

我尝试了以下方法,但没有成功

var reason = $('<%=ReasonPicker.ClientID%> option:selected').text();
var reason = $('<%=ReasonPickerDropDown.ClientID%> option:selected').text();

目前我正在使用下面的代码段来完成任务。

var reason =
$('#ctl00_MainContentPlaceHolder_ReasonPicker_ReasonPickerDropDown
option:selected').text();

我需要通过使用 <%ClientID%> 访问其 ClientID 来完成此任务。帮我。谢谢

  1. 覆盖 WebControl 的 ClientId 属性;
  2. 然后调用 ReasonPicker.ClientID.

示例代码:

public override string ClientID
{
    get
    {
        return ReasonPickerDropDown.ClientID;
    }
}

试试这个

var reason = $('<%=ReasonPicker.ClientID%>').find('select option:selected').text();

var ddlReason =  document.getElementById('<%=ReasonPicker.FindControl("ReasonPickerDropDown").ClientID %>');
var reason = ddlReason.options[ddlReason.selectedIndex].text;