views:

40

answers:

2

In asp.net mvc2, how do I show the status of a user as "online"?

So if the user is actively working on the site, the status would be "online".

if the user stepped away from the site for about 5 minutes then it would be "5 minutes".

if the user stepped away from the site for about 10 minutes then it would be "10 minutes".

So on and so forth.

What is the best way to accomplish this? Any code sample would be very helpful to me.

The responses so far suggest that I used Ajax. If so, then how would I be able to query online users vs offline users. All my queries go against Database. Is it possible to query and display results joining Ajax results with Database queries?

+2  A: 

I would think the most straight forward way of doing it would be with a session variable. You could add a line to your controllers (either in the action method, or the constructor, or even possibly with an action filter) which stashes the current Date/Time in the session. You could then use an ajax call to update the value on the screen at a specific interval. You would probably want to make the interval in minutes rather than seconds otherwise you would be displaying a counter (i.e. "1 second", "2 seconds", etc).

Some quick code samples:

// 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");

Totally not tested, but should be close.

ckramer
+1  A: 

ckramer is right. I suggest expending his solution to make it js degradable.

/ 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")
}
gnome