ASP.NET的DropDownList在后退时不保留所选项目。

问题描述 投票:16回答:2

我有一个ASP的DropDownList,在Page_Load事件中被填充,当我选择一个项目并点击一个按钮后,所选项目被清除,DropDownList中的第一个项目被选中。(DropDownList只有在页面没有回传的时候才会弹出)

if (!IsPostBack)
{
    List<Country> lCountries = new List<Country>();
    List<CompanySchedule> lCompanySchedules = new List<CompanySchedule>();
    this.Load_Countries(lCountries);
    this.Load_Schedules(lCompanySchedules);
    if (personnelRec == null) 
    { 
        personnelRec = new Personnel(); 
    }
    if (Request.QueryString["UA"] != null && Convert.ToInt32(Request.QueryString["UA"].ToString()) > 0)
    {
        userAccount.ID = Convert.ToInt32(Request.QueryString["UA"].ToString());
        App_Database.Snapshift_Select_Helper.SNAPSHIFT_SELECT_PERSONNEL_APP_ACCOUNT(ref userAccount);
    }

    this.imgEmployeePicture.ImageUrl = "./images/Employees/nophoto.gif";
    if (Request.QueryString["EI"] != null && Convert.ToInt32(Request.QueryString["EI"].ToString()) > 0)
    {
            this.Load_PersonnelRec(Convert.ToInt32(Request.QueryString["EI"].ToString()));
    }
    else
    {
        this.lblChangeDirectionHead.Enabled = false;
        this.lblChangeDirections.Enabled = false;
        this.lbSchedules.Disabled = true;
    }
}
asp.net drop-down-menu postback selection
2个回答
36
投票

页面生命周期做了以下工作(还有其他与你的问题无关的步骤)。

  1. OnInit
  2. 从ViewState填充控件(在postback期间)
  3. 设置选定的值(在后退过程中
  4. Page_Load

你需要启用ViewState,这样它才能在 "选择 "项目之前填充列表。 在这种情况下,确保你不会在Page_Load中重新填充而丢失所选的值。 做一些类似于 if (!IsPostback) { // Populate }

否则,你必须手动在 OnInit 事件的每一个页面请求。 Page_Load 在生命周期中太晚了,所以选择的项目会丢失。

编辑。

这个... DropDownList 也必须设置有效值(与浏览器中显示的文本分开)。 这是通过 DataValueField 属性,每个值必须是唯一的。 每个值必须是唯一的,否则只有第一个重复的项目会被选中。 如果你在浏览器中查看HTML源,你应该有。

<select>
    <option value="unique_value1">Displayed text1</option>
    <option value="unique_value2">Displayed text2</option>
</select>

这些唯一的值是用来在服务器端选择正确的项目。


4
投票

你是否使用了一个主页面?如果是,记得在主页面中把EnableViewState设置为true。

© www.soinside.com 2019 - 2024. All rights reserved.