Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 361
Fabio Milheiro Avatar asked Oct 13 '11 21:10

Fabio Milheiro


2 Answers

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

like image 137
Ben Foster Avatar answered Sep 21 '22 13:09

Ben Foster


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.

like image 44
Buildstarted Avatar answered Sep 18 '22 13:09

Buildstarted