Search code examples
javascriptasp.netasp.net-mvcviewbag

MVC: Can I clear ViewBag from Javascript?


I have an action that sends any error message to the Viewbag. When the page loads, at error message in the Viewbag will be presented as a JS alert.

Is there a way in JavaScript to clear the Viewbag? This way, when I get this error and then click somewhere else to get to another page, and then click the BACK button on my browser, the viewbag doesn't still contain anything (including this error message). Right now if I click back, the error message will still appear. I figure if there's a way to clear the ViewBag with JS, this wouldn't happen.


Solution

  • Nope, a ViewBag is completely server side.

    The real issue with this is that the back button won't make another request to your server as this is loaded from the browser's cache.

    You can get around this by making the XHR calls on page load that retrieve the data (rather than sending the data to the client on the initial get request). Once you've done this you can follow @Adriani6's suggestion of using TempData.