2010-07-15 50 views
0

在asp.net mvc2中,我如何显示用户的状态为“在线”?asp.net mvc 2:在线用户

因此,如果用户在网站上积极工作,状态将是“在线”。

如果用户离开站点大约5分钟,那么它将是“5分钟”。

如果用户离开站点大约10分钟,那么它将是“10分钟”。

等等等等。

完成此操作的最佳方法是什么?任何代码示例对我都很有帮助。

答复迄今建议我使用的Ajax。如果是这样,那么我怎么能够查询在线用户与离线用户。我的所有查询都与数据库相反。是否有可能查询并显示结果加入Ajax结果与数据库查询?

回答

2

我认为这样做最直接的方法是使用会话变量。你可以在你的控制器中添加一行(无论是在操作方法中,还是在构造函数中,或者甚至可能有一个操作过滤器),它们将在会话中存储当前的日期/时间。然后,您可以使用ajax调用以特定间隔更新屏幕上的值。您可能希望以分钟而不是秒来间隔,否则您将显示计数器(即“1秒”,“2秒”等)。

一些快速的代码示例:

// Somewhere in controller 
Session["LastSeen"] = DateTime.Now; 

// Now, an action that would return the amount of time since the user was last seen 
public ViewResult GetLastSeenTime() 
{ 
    return Json(new { TimeAway = Date.Time.Now.Subtract((DateTime)Session["LastSeen"]).TotalMinutes}); 
} 

// Then on your page, something like this 
$.post("/Controller/GetLastSeenTime",null,function(result) { 
    if(result.LastSeen < 5) 
     $("#Status").Text("Online"); 
    else if (result.LastSeen % 10 == 0) 
     $("#Status").Text(result.LastSeen + " minutes"); 
},"json"); 

完全没有测试过,但是应该接近。

1

ckramer是对的。我建议花费他的解决方案让它可以降解。

/ Now, an action that would return the amount of time since the user was last seen 
public ActionResult GetLastSeenTime() 
{ 
if (Request.IsAjax) {  
return Json(new { TimeAway = Date.Time.Now.Subtract((DateTime)Session["LastSeen"]).TotalMinutes}); 
} 
ViewData.Add("LastSeen", Date.Time.Now.Subtract((DateTime)Session["LastSeen"]).TotalMinutes})); 
return View("MyView") 
}