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:
If you uncomment the line "ViewData.Clear()" and run the code, below will be the result. It clears the property ViewBag.Message1 & ViewBag.Message2.
2. Clear individual property of ViewBag
Below is the example of how to clear individual property of ViewBag in MVC.
View Code:
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:
<body>
Displayed Text: <br/>
@ViewBag.Message1 <br/>
@ViewBag.Message2
</body>
</html>
public ActionResult Index()
{
ViewBag.Message1 = "MVC Message1";
ViewBag.Message2 = "MVC Message2";
// uncomment it and it will be cleared
//ViewData.Clear();
return View();
}
Result Before:
{
ViewBag.Message1 = "MVC Message1";
ViewBag.Message2 = "MVC Message2";
// uncomment it and it will be cleared
//ViewData.Clear();
return View();
}
Displayed Text:
MVC Message1
MVC Message2
Result After:MVC Message1
MVC Message2
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:<body>
Displayed Text: <br/>
@ViewBag.Message1 <br/>
@ViewBag.Message2
</body>
</html>
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:{
ViewBag.Message1 = "MVC Message1";
ViewBag.Message2 = "MVC Message2";
// uncomment it and it will be cleared
//ViewBag.Message1 = String.Empty;
return View();
}
Displayed Text:
MVC Message1
MVC Message2
Result After:MVC Message1
MVC Message2
Displayed Text:
MVC Message2
MVC Message2
0 Comments