behzad
behzad

Reputation: 43

Why my action filter not work?

I'm new in asp.net mvc, i need detect view page refresh with user and do some thing for that purpose read this:
asp.net mvc - Detecting page refresh
for define action filter right click on controller folder and add RefreshDetectFilter class :

namespace StoreProject.Controllers
{
    public class RefreshDetectFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var cookie = filterContext.HttpContext.Request.Cookies["RefreshFilter"];
            filterContext.RouteData.Values["IsRefreshed"] = cookie != null &&
                                                            cookie.Value == filterContext.HttpContext.Request.Url.ToString();
        }
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.HttpContext.Response.SetCookie(new HttpCookie("RefreshFilter", filterContext.HttpContext.Request.Url.ToString()));
        }
    }
}


and register that in Global.asax,with this way:

GlobalFilters.Filters.Add(new RefreshDetectFilter());


in my action want to use that action filter with this code:

if (RouteData.Values["IsRefreshed"] == true)
            {
                // page has been refreshed.
            }


but i get this error:
enter image description here
How can i solve that problem?thanks.

Upvotes: 0

Views: 582

Answers (1)

Justin Niessner
Justin Niessner

Reputation: 245419

When you read values out of RouteData.Values, you are given an Object rather than a bool. You need to cast to the appropriate type before performing your check.

You also don't need to check against equality with true as the value is already true or false:

if ((bool) RouteData.Values["IsRefreshed"])
{
}

Upvotes: 4

Related Questions