Chase Florell
Chase Florell

Reputation: 47387

ASP.NET MVC: ActionFilterAttribute not setting ViewData

I've written the following ActionFilterAttribute

Imports System.Web.Mvc

Namespace Mvc.Filters
    Public Class StopWatchFilter : Inherits ActionFilterAttribute
        Private tStart As DateTime
        Private tStop As DateTime

        Public Overrides Sub OnActionExecuting( _
            ByVal filterContext As ActionExecutingContext)

            tStart = DateTime.Now

        End Sub

        Public Overrides Sub OnResultExecuted( _
            ByVal filterContext As ResultExecutedContext)

            tStop = DateTime.Now
            filterContext.Controller.ViewData("StopWatch") = _
                ((tStop - tStart).TotalMilliseconds / 1000).ToString(".00")
        End Sub
    End Class
End Namespace

I set in on my controller

''# Fixes SO code coloring
<MyApp.StopWatch()>
Function Index() As ActionResult
    Return View()
End Function

But then when I try to display the ViewData("StopWatch") in my View, it's just blank.

I'm I missing something stupid here?

EDIT:

It appears as though I can set the ViewData in the OnActinExecuting but not in the OnResultExecuted.

So, how on earth might I be able to build a stopwatch ActionFilter?

Upvotes: 1

Views: 2016

Answers (1)

Chase Florell
Chase Florell

Reputation: 47387

Ok, got it.

OnActionExecuted allows me to still write results to the view because the results haven't been executed yet (where OnResultExecuted has already executed the results to the view)!

Imports System.Web.Mvc

Namespace Mvc.Filters
    Public Class StopWatchFilter : Inherits ActionFilterAttribute
        Private tStart As DateTime
        Private tStop As DateTime

        Public Overrides Sub OnActionExecuting(ByVal filterContext As ActionExecutingContext)
            tStart = DateTime.Now
        End Sub

        Public Overrides Sub OnActionExecuted(ByVal filterContext As ActionExecutedContext)
            tStop = DateTime.Now
            filterContext.Controller.ViewData("StopWatch") = ((tStop - tStart).TotalMilliseconds / 1000).ToString(".00")
        End Sub
    End Class
End Namespace

Basically, if you attach the above Attribute to any action, and use ViewData("StopWatch") in your view. You can see how long it took for the Controller Action to execute.

Upvotes: 2

Related Questions