Fabio Milheiro
Fabio Milheiro

Reputation: 8474

How to access ViewData from HttpContext? (ASP.Net MVC)

I don't if this is the right approach, but correct the question if necessary.

I need to access an object through the full page life-cycle that I want to create just once. I thought of using ViewData, but all my extension methods that are accessing context information are using HttpContextBase and thought I should the same for this.

Should I?

Upvotes: 8

Views: 11799

Answers (3)

Ben Foster
Ben Foster

Reputation: 34800

If you want your object to live for a single request only then you can use HttpContextBase.Items.

Upvotes: 21

Buildstarted
Buildstarted

Reputation: 26689

Use @ViewContext.Controller.ViewData to access the ViewData of the current controller. Assuming you want to pull this from the View you're currently in. It would help to see a use-case.

ViewData is part of the WebViewPage and not really something that can be access from HttpContextBase itself.

After reading your comment on the other answer you could use HttpContext.Current.Items to create items that are only available for the current request.

Upvotes: 4

Michael D. Irizarry
Michael D. Irizarry

Reputation: 6302

You can use a Session to store the information and have it available.

HttpContext.Current.Session

Upvotes: -3

Related Questions