简体   繁体   中英

Value of HiddenField to be the Text of DropDownList C#

Using C# I need the value in the Hiddenfield below, which is currently "test" to be the 'Text' of the DropDownList. Any Ideas?

HiddenField hiddenField = new HiddenField { ID = "ValueHiddenField", Value = "test" };

.cs page.

protected void Page_Load(object sender, EventArgs e)
    {
        HiddenField hiddenField = new HiddenField { ID = "ValueHiddenField", Value = "test" };
        theForm.Controls.Add(hiddenField);
        string script = @"function updateCallBackReason() {
                callBackReason = document.getElementById('<%=ValueHiddenField.ClientID %>').value;
                return callBackReason;
            }";
        this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "callBackReasonScript", script, true);

.aspx

<asp:label runat="server" ID="lblCallbackReason" AssociatedControlID="dropCallbackReason" CssClass="textLabel">Reason for callback:</asp:label>
            <asp:DropDownList runat="server" ID="dropCallbackReason" onChange="updateCallBackReason" ClientIDMode="Static" >
                <asp:ListItem Text="-- Select Reason --" Value="1"></asp:ListItem>
                <asp:ListItem Text="Booking a Test Drive" Value="6"></asp:ListItem>
                <asp:ListItem Text="Discussing a Purchase" Value="11"></asp:ListItem>
                <asp:ListItem Text="Contract Hire Quotation" Value="45"></asp:ListItem>
            </asp:DropDownList>

I'd say your function updateCallBackReason is not doing what is supposed to do (update hidden field value). If didn't get wrong your question, this is what you have to do.

string script = string.Format(@"function updateCallBackReason() {{
    var ddl = document.getElementById('dropCallbackReason');
    var callBackReason = document.getElementById('{0}');
    callBackReason.value = ddl.options[ddl.selectedIndex].innerHTML;
}}", hiddenField.ClientID );

将下拉列表绑定到数据源后,将下拉列表的选定值设置为隐藏字段中文本的索引。

dropCallbackReason.SelectedIndex = dropCallbackReason.Items.IndexOf(dropCallbackReason.Items.FindByText(ValueHiddenField.Value.ToString()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM