You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Web Forms点击Reserve时availableRooms列表为空的问题求助

问题原因

ASP.NET Web Forms是无状态框架,每次点击按钮触发回发时,页面类会重新实例化。你定义的availableRooms如果是页面的普通成员变量,会被重新初始化为空列表,因此点击Reserve按钮时无法获取之前搜索到的房间数据。

解决方案:用ViewState保存房间列表

ViewState是ASP.NET内置的页面状态存储机制,能在回发时保留数据,适合存储这类页面级的小体量数据。

步骤1:让Room类支持序列化

ViewState需要序列化对象,给你的Room类添加[Serializable]特性:

[Serializable]
public class Room
{
    public int roomID { get; set; }
    public string roomName { get; set; }
    public string roomType { get; set; }
    public bool enSuite { get; set; }
    public float ppNight { get; set; }
    public float ppAddAdult { get; set; }
    public float ppAddChild { get; set; }
    public int lengthStay { get; set; }
    public float price { get; set; }

    // 你的GetPrice方法
    public float GetPrice(int adultCount, int childCount)
    {
        // 原有逻辑
    }
}

步骤2:用ViewState封装availableRooms

把原来的availableRooms字段替换为依赖ViewState的属性:

// 替换原来的List<Room> availableRooms;定义
private List<Room> availableRooms
{
    get
    {
        // 如果ViewState中没有数据,初始化空列表
        if (ViewState["AvailableRooms"] == null)
        {
            ViewState["AvailableRooms"] = new List<Room>();
        }
        return (List<Room>)ViewState["AvailableRooms"];
    }
    set
    {
        ViewState["AvailableRooms"] = value;
    }
}

步骤3:保留原有搜索逻辑

你的BtnSearch_Click方法无需大幅修改,填充availableRooms的逻辑会自动将数据存入ViewState:

// 原有BtnSearch_Click中的填充逻辑保持不变
availableRooms.Add(room);
// ...
gridViewRooms.DataSource = availableRooms;
gridViewRooms.DataBind();

步骤4:正常使用Reserve按钮逻辑

现在点击Reserve按钮时,availableRooms会从ViewState中读取之前保存的列表,能正常找到选中的房间:

protected void gridViewRooms_reserveCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Reserve")
    {
        using (MySqlConnection connection = new MySqlConnection(connectionString))
        {
            try
            {
                connection.Open();
                int accountID = 0;
                DateTime checkOutDate = Convert.ToDateTime(checkOut.Text);
                DateTime checkInDate = Convert.ToDateTime(checkIn.Text);

                int rowID = Convert.ToInt32(e.CommandArgument);
                Room selectedRoom = availableRooms.Find(room => room.roomID == rowID);
                // 后续预订逻辑...
            }
            catch (Exception ex)
            {
                // 异常处理
            }
        }
    }
}
其他可选方案

如果房间数据量较大,ViewState会增加页面体积,可选择:

  • 回发时重新查询数据库:在Reserve按钮事件中,根据rowID直接查询单条房间数据,无需依赖整个列表
  • 用Session存储:将availableRooms存入Session,但要注意Session过期和内存占用问题

内容的提问来源于stack exchange,提问作者jwykesss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 19:10:35