Run a method just once in controller RRS feed

  • Question

  • User-403790330 posted

    I have method in a controller to run but every time the view reload the method run again. I tired running it from the application_start I got the same result every time the view reload, it the method runs again. How can I do it to just run once?.

    Tuesday, November 22, 2016 11:29 PM

All replies

  • User-707554951 posted

    Hi omoOba14,

    From your description, I suggest you could do as the code below:

    public static bool flag = true;
            public ActionResult Index3()
                if (flag)
                    //call the method
                    ViewBag.Message = "Fist time load";
                    ViewBag.Message = "Second time load";
                flag = false;
                return View();

    Best regards


    Wednesday, November 23, 2016 11:55 AM
  • User-403790330 posted

    Thank you very much, I want to ask does it state persist even when the view associate with ActionResult reload.

    Wednesday, November 23, 2016 12:02 PM
  • User303363814 posted

    Do you mean to run the code once in the lifetime of the universe?

    Or once everytime the web server starts?

    Or once everytime the web site starts?

    Or once everytime a new user comes to the site?

    Or something else?

    Wednesday, November 23, 2016 10:38 PM
  • User753101303 posted


    No the web is stateless and won't persist anything unless asking for this explicitely (if coming from Web Forms, it uses an hidden field to automatically persist few things for you).

    Also doing that from Application_Start doesn't seems to make sense. I'm really not sure what you are trying to do. A possible option might be to "cache" this page but for now I would suggest to explain what is your final goal.

    Thursday, November 24, 2016 12:06 PM