Sam Axe
Sam Axe

Reputation: 33738

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.

Upvotes: 0

Views: 2362

Answers (1)

Rob
Rob

Reputation: 1328

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.

Upvotes: 2

Related Questions