How to Clear ViewBag in ASP.Net MVC

ViewBag uses dynamic property, internally it uses ViewData. Due to your functional needs you might wan't hide or clear the ViewBag / ViewData.

Read : Difference between ViewBag vs ViewData vs TempData vs Session in MVC

1. Clear All properties of ViewBag:
Below is the example of how to clear ViewBag in MVC. It will clear all the properties created in ViewBag.

View Code:
<html lang="en">
<body>
Displayed Text: <br/>
@ViewBag.Message1 <br/>
@ViewBag.Message2
</body>
</html>
Action Method Code:
public ActionResult Index()
{
ViewBag.Message1 = "MVC Message1";
ViewBag.Message2 = "MVC Message2";
// uncomment it and it will be cleared
//ViewData.Clear();
return View();
}
Result Before:
Displayed Text:
MVC Message1
MVC Message2
Result After:
If you uncomment the line "ViewData.Clear()" and run the code, below will be the result. It clears the property ViewBag.Message1 & ViewBag.Message2.
Displayed Text:

2. Clear individual property of ViewBag
Below is the example of how to clear individual property of ViewBag in MVC.

View Code:
<html lang="en">
<body>
Displayed Text: <br/>
@ViewBag.Message1 <br/>
@ViewBag.Message2
</body>
</html>
Action Method Code:
public ActionResult Index()
{
ViewBag.Message1 = "MVC Message1";
ViewBag.Message2 = "MVC Message2";
// uncomment it and it will be cleared
//ViewBag.Message1 = String.Empty;
return View();
}
Result Before:
Displayed Text:
MVC Message1
MVC Message2
Result After:
Displayed Text:
MVC Message2

Post a Comment

0 Comments