ASP.NET C#中的会话持续时间

时间:2016-03-07 02:57:45

标签: c# asp.net

我是ASP.NET新手,我试图从页面加载时间到单击按钮结束会话的时间找到会话持续时间。我试图使用DateTime和TimeSpan,但问题是在另一个事件中无法访问在一个事件中生成的DateTime值。

'// Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication17
{
public partial class WebForm1 : System.Web.UI.Page
 {
    //DateTime tstart, tnow, tend;


    protected void Page_Load(object sender, EventArgs e)
    {


    }

    // Button to Start the Session
    public void begin_Click(object sender, EventArgs e)
    {
        DateTime tstart = DateTime.Now;
        SesStart.Text = tstart.ToString();
    }

   // To Display the Present Time in UpdatePanel using AJAX Timer
          protected void Timer1_Tick(object sender, EventArgs e)
    {
        DateTime tnow = DateTime.Now;
        PresTime.Text = tnow.ToString();

    }

   // Button to end the Session
    public void end_Click(object sender, EventArgs e)
    {
        DateTime tend = DateTime.Now;

    //The Problem exists here. the value of tstart is taken by default as                
        TimeSpan tspan = tend - tstart;


        SesEnd.Text = tend.ToString();
        Dur.Text = Convert.ToString(tstart);

          }
      } 
     }'

3 个答案:

答案 0 :(得分:1)

您可以使用Session变量来解决此问题。您需要在调用begin_Click事件时设置会话变量值。

 public void begin_Click(object sender, EventArgs e)
{
    DateTime tstart = DateTime.Now;
    SesStart.Text = tstart.ToString();
    Session["BeginEnd"] = tstart;
}

单击end_Click的时间执行此操作

public void end_Click(object sender, EventArgs e)
{
    DateTime tend = DateTime.Now;
    DateTime tstart = Convert.ToDateTime(Session["BeginEnd"]);
    TimeSpan tspan = tend - tstart;
    SesEnd.Text = tend.ToString();
    Dur.Text = Convert.ToString(tstart);
 }

答案 1 :(得分:0)

您需要在会话

中保存开始时间
// Button to Start the Session
public void begin_Click(object sender, EventArgs e)
{
    DateTime tstart = DateTime.Now;
    SesStart.Text = tstart.ToString();
    Session["StartTime"] = tStart;
}

并在end_Click

中使用它
// Button to end the Session
public void end_Click(object sender, EventArgs e)
{
    DateTime tend = DateTime.Now;
    var tstart = Session["StartTime"] as DateTime; // see this                      
    TimeSpan tspan = tend - tstart;
    SesEnd.Text = tend.ToString();
    Dur.Text = Convert.ToString(tstart);
 }

答案 2 :(得分:0)

使用Session是最好的方法。由于您的页面已回发,因此它将丢失任何临时保留值。

  1. on开始创建会话[" time1"] = DateTime.Now;
  2. on Stop从会话中检索值DateTime dt = Session [" time1"];
  3. 如果您需要任何其他说明,请与我们联系。