ASP.NET MVC:ActionFilterAttribute 未设置 ViewData
以下 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")
时,它只是空白。
我在这里错过了一些愚蠢的事情吗?
编辑:
看来我可以在 OnActinExecuting
中设置 ViewData
,但在 OnResultExecuted
中不能。
那么,我到底如何才能构建一个秒表 ActionFilter
呢?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,明白了。
OnActionExecuted
允许我仍然将结果写入视图,因为结果尚未执行(其中OnResultExecuted
已经将结果执行到视图)!基本上,如果您将上述属性附加到任何操作,并在视图中使用
ViewData("StopWatch")
。您可以看到控制器操作执行需要多长时间。Ok, got it.
OnActionExecuted
allows me to still write results to the view because the results haven't been executed yet (whereOnResultExecuted
has already executed the results to the view)!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.