Introduction
In Asp.Net MVC there are three ways to pass/store data between the controllers and views.
ViewData
In Asp.Net MVC there are three ways to pass/store data between the controllers and views.
ViewData
- ViewData is used to pass data from controller to view
- It is derived from ViewDataDictionary class
- It is available for the current request only
- Requires typecasting for complex data type and checks for null values to avoid error
- If redirection occurs, then its value becomes null
ViewBag
- ViewBag is also used to pass data from the controller to the respective view
- ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
- It is also available for the current request only
- If redirection occurs, then its value becomes null
- Doesn’t require typecasting for complex data type
TempData
- TempData is derived from TempDataDictionary class
- TempData is used to pass data from the current request to the next request
- It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
- It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages
- Keep and Peek methods are used to preserve/get value of Tempdata using-tempdata-peek-and-keep-in-Asp-Net-mvc/
Example :
Controller Action:
Controller Action:
public ActionResult Index()
{
var model = new LoginModel()
{
UserName = "hello",
Password="1",
RememberMe =true
};
List<LoginModel> log = new List<Models.LoginModel>();
log.Add(model);
TempData["ModelName"] = log;
ViewBag.Name = log;
ViewData["Name"] = log;
return View();
}
View :
<ul>
@foreach (var item in TempData["ModelName"] as List<mvc1.Models.LoginModel>)
{
<li>
@item.UserName
</li>
}
</ul>
<br />
<ul>
@foreach (dynamic item in ViewBag.Name) @*No Typecast*@
{
<li>
@item.UserName
</li>
}
</ul>
<br />
<ul>
@foreach (var item in ViewData["Name"] as List<mvc1.Models.LoginModel>) @*Typecast*@
{
<li>
@item.UserName
</li>
}
</ul>
0 comments:
Post a Comment