简体   繁体   中英

How to get the current ViewContext in MVC

So I've got a bit of data that I'm poking into ViewContext.ViewData from _ViewStart.vbhtml.

Something like: ViewContext.ViewData("__Stuff") = stuffObject

Now from a class that has no concept of Views or MVC or anything web-framework related, I'd like to grab the current ViewContext.

Similar to how you can do HttpContext.Current , I'd like some way of asking for the current ViewContext .

So far my searches through HttpContext have not yielded results.

Yes, I am aware that I can inject the ViewContext from the View that needs this data. But that is less desirable than having a function that can find it without this injection.

I think you may be out of luck. Typically, as you probably know, the view is the end of the line. Most components do not know what view is going to run until it does. I know you are reluctant to pass the information in, but maybe you can use something like an actionfilter to add the information to the HttpContext.

Public Class ViewDataInjectionAttribute
    Inherits ActionFilterAttribute

    Public Overrides Sub OnActionExecuted(ctx As ActionExecutedContext)

        Dim result = TryCast(ctx.Result, ViewResult)
        If result IsNot Nothing Then
            HttpContext.Current.Items("viewData") = result.ViewData
        End If

        MyBase.OnActionExecuted(ctx)
    End Sub

End Class

Then, you can apply the filter at the action, controller, or even globally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM