如果页面刷新,如何停止运行page_load事件

时间:2009-07-03 11:46:15

标签: asp.net vb.net

每次加载我的网页时,它都会在页面的page_load事件中运行一个例程,后面会将viewcount增加1。

我遇到的问题是,即使使用刷新来重新加载页面,例程也会运行。

如果特定用户在当前会话中查看了该页面,如何停止此例程?

我以为我可以使用:

If Not Page.IsPostBack Then
(run the routine)

但它似乎不起作用。

我是否需要使用会话状态或cookie等?

2 个答案:

答案 0 :(得分:2)

If Not Page.IsPostback仅在用户点击该页面上的按钮时才有用。如果用户只刷新页面(如使用F5),它将无法正常工作。 问题是

  • 如果用户在访问您网站上的其他页面(即主页 - >产品页面 - >主页)后返回该页面,是否要添加到该计数器。

您可以使用Dictionary并将其存储在用户的Session中。字典将是Dictionary<string, int>类型的字典。当用户访问该页面时,您将检索该字典并查看当前页面是否已存在条目+查询字符串(字符串Key)。

如果没有,请添加它。然后,如果用户在首次转到另一个页面后重新访问该页面,则是否要增加该页面的计数(或者不是)。

您可以使用:Request.UrlReferrer

检查用户是否来自其他网址

答案 1 :(得分:1)

您可以记录用户是否访问了会话中的页面。您可以在页面路径下的会话中放置一个bool。通过这种方式,它可以适用于个人用户,并且会在会话期间工作。

要记录用户访问过该页面,您可以执行以下操作:

HttpContext.Current.Session[pagePath] = true;

并了解用户是否访问了该页面,您可以执行此操作:

bool hasUserVisitedPage = (bool)HttpContext.Current.Session[pagePath];

以下是它在页面加载中的组合方式:

protected void Page_Load(object sender, EventArgs e)
{
    //set the default for whether the user visited the page
    bool hasUserVisitedPage = false;
    //get the path of the page
    string pagePath = HttpContext.Current.Request.Url.LocalPath;

    //find out if the user visited the page by looking in the session
    try { hasUserVisitedPage = (bool)HttpContext.Current.Session[pagePath]; }
    //we don't care if the value wasn't present (and therefore didn't cast)
    catch {}

    //if the user hasn't visited the page before
    if (!hasUserVisitedPage )
    {
        //record that the page has now been visited
        HttpContext.Current.Session[pagePath] = true;

        //put the rest of your load logic here...
    }
}

如果你想在多个页面上加入这种技术,我会将这个功能封装到一个帮助类中,这样你就不用重复了。

public static class PageHelper
{
    public static bool hasPageBeenViewed()
    {
        //set the default for whether the user visited the page
        bool hasUserVisitedPage = false;
        //get the path of the page
        string pagePath = HttpContext.Current.Request.Url.LocalPath;

        //find out if the user visited the page by looking in the session
        try { hasUserVisitedPage = (bool)HttpContext.Current.Session[pagePath]; }
        //we don't care if the value wasn't present (and therefore didn't cast)
        catch {}

        //if the user hasn't visited the page before
        if (!hasUserVisitedPage )
        {
            //record that the page has now been visited
            HttpContext.Current.Session[pagePath] = true;
        }

        return hasUserVisitedPage;
    }
}

然后它会大大简化以下的加载逻辑: (这将为您提供逻辑位于中心位置的额外好处,如果您需要更改它将非常方便)

protected void Page_Load(object sender, EventArgs e)
{
    //if the user hasn't visited the page before
    if (!PageHelper.hasPageBeenViewed())
    {            
        //put the rest of your load logic here...
    }
}
相关问题