简体   繁体   中英

Button and DropDownList using Session/Application Variable in ASP.NET, C#

How would I implement this scenario? I have two buttons, Button1 and Button2, on the Default page. If Button1 is clicked, the contents of the DropDownList on the second page would be: a, b, and c. However, if Button2 is clicked from the Default page, the contents of the DDL on the second page would be: d and e. Thank you!

If you are using ASP.NET WebForms, you could populate a Session variable within your first page, with the contents being determined when either button is clicked. I would then set the DataSource for the DropDown list to the Session variable. Something like this:

Page 1:

protected void Button1_Click(object sender, EventArgs e)
    {
        Session["ListSource"] = new List<string>
        {
            "a",
            "b",
            "c"
        };
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Session["ListSource"] = new List<string>
        {
            "d",
            "e"
        };
    }

Page 2:

        protected void Page_Load(object sender, EventArgs e)
    {
        DropDownList1.DataSource = (List<string>)Session["ListSource"];
        DropDownList1.DataBind();
    }

In MVC, you could have a Controller action generate the List and provide it as the model to your second page. Given you are referring to a DropDownList, though, it sounds like you are using WebForms.

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