试图将选定的下拉列表传递到会话

本文关键字:会话 下拉列表 | 更新日期: 2023-09-27 18:15:35

我试图将下拉列表的值传递给会话变量,然后将此值转换为查看页面的文本标签。然后需要将该值传递给sql表(这不是问题)。问题在于每次我试图调用标签中的下拉列表的值(或索引,我已经尝试了两者)时,我都会得到一个空异常。这是我在第一页上的一个下拉菜单的代码,并尝试将其从创建的会话绑定到下一个:FirstPage.aspx

<asp:DropDownList ID="ddlInnoc" runat="server">
<asp:ListItem Value="0">No</asp:ListItem>
<asp:ListItem Value="1">Yes</asp:ListItem>
</asp:DropDownList>

FirstPage.aspx.cs

Session["Jabs"] = ddlInnoc.SelectedIndex;

SecondPage.aspx

<asp:Label ID="lblJabs" runat="server"></asp:Label>

SecondPage.aspx.cs

lblJabs.Text = Session["Jabs"].ToString();
请告诉我,我只是在犯傻!我收到的异常如下:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error: 

Line 11:     {
Line 12:         //Capture session values from previous page and send to relevant    labels
Line 13:         **lblGroup.Text = Session["NoInGroup"].ToString();**
Line 14:         lblFirstName.Text = Session["FirstName"].ToString();
Line 15:         lblMiddleName.Text = Session["MiddleName"].ToString();

有点奇怪的是,我可以成功地抓取不同页面上不同下拉列表的selecteindex。它让我的头发都要掉下来了!

试图将选定的下拉列表传递到会话

确保在打开第二页之前进行回发。Session["Jabs"] = ddlInnoc.SelectedIndex;应在所选的dexchanged方法中,并且在下拉列表中设置autpostback,例如:

<asp:DropDownList ID="ddlInnoc" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlInnoc_SelectedIndexChanged">
   <asp:ListItem Value="0">No</asp:ListItem>
   <asp:ListItem Value="1">Yes</asp:ListItem>
</asp:DropDownList>

,方法是这样的:

protected void ddlProject_SelectedIndexChanged(object sender, EventArgs e)
{
    //if you want "0" or "1"
    Session["Jabs"] = ddlInnoc.SelectedIndex;
    //if you want "Yes" or "No"
    //Session["Jabs"] = ddlInnoc.SelectedItem.Text;
    //also if you want "0" or "1"
    //Session["Jabs"] = ddlInnoc.SelectedValue;
}

在大多数情况下,你可能不需要选择索引,因为这只是下拉列表中项目的顺序

要确保会话总是被填满,可以将其设置在Page_Load:

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
      Session["Jabs"] = ddlInnoc.SelectedIndex;
   }
}

还有:当使用Session时,你应该始终意识到Session可能会过期,所以在使用之前你应该总是检查NULL:

SecondPage.aspx.cs

lblJabs.Text = (Session["Jabs"] == null ? "Default Value" : Session["Jabs"].ToString());