What is ViewData , ViewBag and TempData in MVC
ViewData:-
- ViewData is a dictionary object that is derived from the ViewDataDictionary class.
- ViewData is a property of the ControllerBase class.
- Viewdata is used to transfer data from controller to view.
- It’s required typecasting for getting data and check for null values to avoid an error.
the syntax for ViewData is:-
ViewData["Message"] = "your Message";
ViewBag:-
- ViewBag is a dynamic property that is used to transfer data from controller to view.
- ViewBag is a property of the ControllerBase class.
- ViewBag doesn’t require typecasting for getting data and check for null values.
the syntax for ViewBag is:-
ViewBag.Message= "your Message";
ViewBag & ViewData Example:
public ActionResult Index()
{
ViewBag.Message = "Your Messsage";
return View();
}
public ActionResult Index()
{
ViewData["Message"] = "Your Message";
return View();
}
In View:-
@ViewBag.Message
@ViewData["Message"]
TempData:-
- TempData is a dictionary object that is derived from the TempDataDictionary class and stored in short lives session and it is string key and object value.
- TempData is a property of the ControllerBase class.
- It is Used to transfer data from one controller to another controller or from one action to another action method
- TempData required typecasting for getting data and check for null values to avoid an error.
public ActionResult Index()
{
TempData["Message"] = "Your Message";
return View();
}
In View:-
@TempData["Message"]
Comments
Post a Comment