User
User

Reputation: 30985

Need to store a static value for the duration of a request. How?

I have an ASP.NET MVC application. I have come to an idea of generating autoincremented values to be used as unique element ids. The question is, how can I have and work with a global variable which should be there for the duration of a request (page generation) but no longer?

I thought of using TempData for this shared variable and then just delete this key when the page is done. But then, where in code to purge this TempData key? Obviously it has to be some very last piece of code where the page has been rendered already.

Any input is highly appreciated.

EDIT: I have a number of HTML helpers that can be called from various views and partial views, so declaring a variable on a page and passing it to each helper is obviously not a good solution. I wish to just use the helpers and know they all are getting unique ids behind the scenes.

Upvotes: 0

Views: 284

Answers (5)

User
User

Reputation: 30985

Okay, I have googled a little bit and found a solution on ASP.NET forums.

http://forums.asp.net/t/1401685.aspx

Obviously, I can use the HttpContext.Current.Items collection to have my little static variable for the duration of a request.

Upvotes: 1

John Rasch
John Rasch

Reputation: 63465

You could create a member variable in your controller which would be regenerated for each request:

public class ItemController : Controller 
{

    private int _UniqueID = 0;

    public ActionResult Index()  
    {
         foreach (var item in items)
         {
              item.UniqueID = _UniqueID++;
         }
         // etc...
    }

Upvotes: 0

Chris Shaffer
Chris Shaffer

Reputation: 32575

I would imagine you could use the Application_BeginRequest and Application_EndRequest methods in global.asax.cs; Note I can't double check the method names currently, but I think they are close.

Upvotes: 0

Robert Koritnik
Robert Koritnik

Reputation: 105059

Why don't you define your integer variable at the top of the page view file? Use it throughout the view rendering execution and at the end of it you can easily leave it as is. You don't have to explicitly destroy anything. Your variables live for the duration of request only. IIS is stateless service (if you subtract Session, Cache and Application variables) so it doesn't really remember anything explicitly.

Upvotes: 0

Serhat Ozgel
Serhat Ozgel

Reputation: 23766

If all you need is to store a number, the resources that would take to manage its lifestyle would take a lot more than just having a one static integer and always reusing it.

Do not bother deleting the key after each request. Just use a static (I think this is shared in visual basic) integer, use and increment it every time you need a unique value. Also take its mod with a ridiculously high number each time to make sure it will not be reused in a single request and it will never overflow.

Upvotes: 0

Related Questions