您所在的位置: 首页 >> 常见问题 >> Web应用程序设计(ASP.NET) >> 正文

[ASP.NET]如何将数据从一个页面传送给另外一个页面
发表日期:2010年3月30日   作者:whitewin   点击:
【Question】在实验3的“宾馆住宿系统”的设计中,你要求在一个页面输入旅客的住宿信息,提交以后,在另外一个页面上显示出旅客信息及总价,以便于打印发票,这如何实现?
【Answer】当你为提交按钮设置PostBackUrl属性时,点击这个按钮时,页面就会转向另外一个页面,同时,本页面的信息也会通过ViewStates(视图状态)传递过去。在另外一个页面中,可以使用PreviousPage属性获取上一网页的信息。
示例页面(Hotel.aspx)中,提交按钮的PostBackUrl属性设置为同一文件夹下的HotelResult.aspx页面。在HotelResult.aspx页面的Page_Load事件中,有以下代码,这些代码通过PreviousPage属性取出前一网页每个控件的值,并时行计算,将结果显示出来:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (PreviousPage == null) return;
        // 获取旅客姓名
        TextBox tbName = PreviousPage.FindControl("tbName") as TextBox;
        lblName.Text = tbName.Text;
        // 获取旅客性别
        RadioButtonList rbSex = PreviousPage.FindControl("rbSex") as RadioButtonList;
        lblSex.Text = rbSex.SelectedItem.Text;
        // 获取旅客身份证号
        TextBox tbID = PreviousPage.FindControl("tbID") as TextBox;
        lblID.Text = tbID.Text;
        // 获取客房等级和单价
        DropDownList ddlRate = PreviousPage.FindControl("ddlRate") as DropDownList;
        lblType.Text = ddlRate.SelectedItem.Text;
        lblPrice.Text = ddlRate.SelectedValue;
        // 获取住宿天数
        TextBox tbDays = PreviousPage.FindControl("tbDays") as TextBox;
        lblDays.Text = tbDays.Text;
 
        // 计算总价格
        int days = int.Parse(tbDays.Text);
        int price = int.Parse(ddlRate.SelectedValue);
        int total = price * days;
 
        lblTotal.Text = total.ToString("C") + "元";
}