我编写了以下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
我进入我的控制器
''# Fixes SO code coloring
<MyApp.StopWatch()>
Function Index() As ActionResult
Return View()
End Function
但是当我尝试在我的视图中显示ViewData("StopWatch")
时,它只是空白。
我在这里错过了一些愚蠢的东西?
似乎我可以在ViewData
中设置OnActinExecuting
,但在OnResultExecuted
中设置不。
那么,我怎么能够建立一个秒表ActionFilter
?
答案 0 :(得分:2)
好的,明白了。
OnActionExecuted
允许我仍然将结果写入视图,因为结果尚未执行(其中OnResultExecuted
已将结果执行到视图中)!
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
基本上,如果您将上述属性附加到任何操作,并在视图中使用ViewData("StopWatch")
。您可以看到Controller Action执行所需的时间。