Harsha W
Harsha W

Reputation: 3366

How to acquire the ClientID of User Control Drop Down List

I have created a user control containing a drop down list. I am unable to acquire the ClientID in order to get the selected value or text.

Implementation

<%@ 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 file

<%@ 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>

I tried the following methods but no luck

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

Currently I am using the below code segment in order to complete the task.

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

I need to do this task by accessing its ClientID using <%ClientID%>. Help Me. Thanks

Upvotes: 2

Views: 2000

Answers (2)

Johan Shen
Johan Shen

Reputation: 168

  1. override WebControl's ClientId property;
  2. then call ReasonPicker.ClientID.

sample code:

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

Upvotes: 1

Mudassir Hasan
Mudassir Hasan

Reputation: 28771

Try this

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

OR

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

Upvotes: 2

Related Questions