0

i have a website where the user can enter a message in a textbox, he can press submit and the text gets to a controller and there i put it in a viewbag. I want to display the message from the viewbag in every view but after refreshing the site, the viewbag gets empty.

Is there another way to display a message in every view?

sikk456
  • 1
  • 1
  • Does this answer your question? [ViewBag, ViewData and TempData](https://stackoverflow.com/questions/7993263/viewbag-viewdata-and-tempdata) – शेखर Mar 23 '21 at 12:28
  • Thanks for the help, but i need a way to display my message permanently, with TempData, ViewData and ViewBag the message vanished – sikk456 Mar 23 '21 at 12:39

1 Answers1

0

You could use TempData.Peek(string key).

Put some message to TempData:

TempData["message"] = string.Format("{0} has been saved", "...");

Retrieve message in the View using Peek:

@if (TempData.Peek("message") != null) {
  <div>@TempData.Peek("message")</div>
}

Peek returns an object that contains the element that is associated with the specified key, without marking the key for deletion. So if your refresh the page, the key remains in TempData - it will survive for multiple redirects.

TempData data is restricted to a single user’s session (so that users do not see each other’s TempData)

nkl
  • 38
  • 6