隐藏字段的值是DropDownList C#的文本

时间:2013-06-12 15:43:18

标签: c# asp.net drop-down-menu hiddenfield

使用C#我需要下面的Hiddenfield中的值,该值当前是“test”,是DropDownList的“Text”。任何想法?

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

.cs页面。

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>

2 个答案:

答案 0 :(得分:0)

我会说你的函数updateCallBackReason没有做应该做的事情(更新隐藏字段值)。如果您的问题没有出错,那就是您必须要做的事情。

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 );

答案 1 :(得分:0)

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

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