简体   繁体   English

下拉列表选择的值重置为第一项

[英]Dropdownlist selected value is reset to first item

I have tried to look through many questions about the dropdownlist and still yet to resolve my issue. 我试图浏览有关下拉列表的许多问题,但仍未解决我的问题。

I have a Dropdownlist and a Submit button. 我有一个下拉列表和一个提交按钮。 When Submit button is clicked after value selected, it should update the Label text with the selected value of the Dropdownlist. 选择值后单击“提交”按钮时,它将使用“下拉列表”的所选值更新“标签”文本。 However, what happened was each time value is selected from dropdown, it refreshes the page and the value captured was the first item in dropdownlist. 但是,发生的事情是每次从下拉列表中选择值时,都会刷新页面,并且捕获的值是下拉列表中的第一项。 How do I capture the selected value correctly before it refreshes? 如何在刷新之前正确捕获所选值?

Am at wits end, not sure where went wrong. 我机智,不确定哪里出了问题。

*All items in dropdownlist are unique. *下拉列表中的所有项目都是唯一的。 No duplication. 没有重复。

My codes: 我的代码:

ASP.NET ASP.NET

<form id="form1" runat="server">
        <asp:DropDownList ID="ddlCode" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlCode_SelectedIndexChanged"/>
        <br />
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"/>
        <asp:UpdateProgress ID="updProgress" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
            <ProgressTemplate>
                <img alt="progress" src="img/loading.gif"/><br /><h2>Loading...</h2> 
            </ProgressTemplate>
        </asp:UpdateProgress>

        <br />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" >
            <ContentTemplate>

                <asp:Button ID="submitBtn" runat="server" cssclass="btn btn-success" OnClick="submitBtn_Click" Text="Submit"/>
                <asp:Label ID="lblCode" runat="server"/>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="ddlCode" EventName="SelectedIndexChanged"/>
            </Triggers>
        </asp:UpdatePanel>
    </form>

Code behind 后面的代码

string ddlSelectedIndex = "";   

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
      //This is to load code into dropdownlist which works fine. 
      LoadCode();
   }
}

protected void ddlCode_SelectedIndexChanged(object sender, EventArgs e)
{ 
     ddlSelectedIndex =(ddlCode.Items[ddlCode.SelectedIndex].Text).Substring(0, 4);
}


protected void submitBtn_Click(object sender, EventArgs e)
{
     lblCode.Text = ddlSelectedIndex;
}

Try it without the "AutoPostBack=True" on the DropDownList... the way your code is written, it causes the page to refresh any time the DropDownList value changes. 尝试在DropDownList上没有“ AutoPostBack = True”的情况下进行尝试...以编写代码的方式,只要DropDownList值更改,它就会刷新页面。 What you want is a postback when submit is clicked. 您想要的是单击提交时的回发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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