在回发之间保留ddl值和选定值

时间:2016-08-02 22:58:27

标签: c# asp.net

我在页面上有一个保存按钮和一个下拉列表。在页面加载内,如果!Page.PostBack(AutoPostBack = false),则会填充下拉列表。因此,第一次加载页面时,会填充下拉列表。我还有一个保存方法来使用保存按钮。单击此按钮时,它应该使用下拉列表的选定值执行某些操作。我的问题是下拉列表在按钮保存方法中没有值(为空)。你会如何解决这个问题?

标记:

MyClass.aspx

<%@ Page Language="C#" AutoEventWireup="true" Inherits="MyClass"  %>


<asp:Content ID="Content3" ContentPlaceHolderID="MainRegion" runat="server">

<div>

<asp:DropDownList ID="myDdl" runat="server" OnSelectedIndexChanged="myDdlChange" ViewStateMode="Enabled" EnableViewState="true" />
</div>
<br />

<div style="min-width: 300px; max-width: 770px;">
<asp:TextBox id="txtBox" runat="server" TextMode="MultiLine" />
</div>

<div class="buttonContainer">
    <span >
        <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click"  />   
    </span>
</div>

</asp:Content>

然后,在后面的代码中:

MyClass.aspx.cs

public class MyClass
    {
        protected global::System.Web.UI.WebControls.DropDownList myDdl;
        protected global::System.Web.UI.WebControls.TextBox txtBox;
        protected global::System.Web.UI.WebControls.Button btnSave;


        protected override void OnLoad(EventArgs e)
        {

            base.OnLoad(e);

            if (this.Page.IsPostBack)
                Session["selectedID"] = myDdl.SelectedValue; // my attempt to put the selected value from ddl in a session var, to use it later inside the save method but it didn't work

            if (!Page.IsPostBack)
            {
                //create array1 here
                myDdl.Items.Clear();
                myDdl.Items.AddRange(array1); 
                Session["selectedID"] = myDdl.SelectedValue;

                myDdlChange(null, null);
                this.DataBind();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {

            //do something based on myDdl.SelectedValue (which shouldn't be null)

        }

        protected void myDdlChange(object source, EventArgs e)
        {

            txtBox.Text = myDdl.SelectedValue;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我认为主要问题是你应该使用Page_Load代替OnLoad

您不需要使用Session来记住SelectedValue。

尝试这样对我有用的东西......

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
        PopulateDropdown();
}

private void PopulateDropdown()
{
    myDdl.Items.Clear();
    var array1 = new ListItem[3];
    array1[0] = new ListItem("item1", "item1");
    array1[1] = new ListItem("item2", "item2");
    array1[2] = new ListItem("item3", "item3");
    myDdl.Items.AddRange(array1);
    myDdl.DataBind();
}

protected void btnSave_Click(object sender, EventArgs e)
{
    var selectedVal = myDdl.SelectedValue;  // putting a breakpoint here shows myDdl.SelectedValue is not null
}

protected void myDdlChange(object sender, EventArgs e)
{

}