ViewBag, ViewData and TempData - ablealias/MVC GitHub Wiki

ViewBag

ViewBag is a property of ControllerBase class, which is the base class of all the controllers. The ViewBag property enables you to dynamically share values from the controller to the view. ViewBag can be useful when you want to transfer temporary data (which is not included in the model) from the controller to the view. If the user wants to transfer some data to view from the controller, you simply define a dynamic property of the ViewBag and assign the value to the property. For example, controller define a dynamic property in ViewBag called MyMessageToView,
ViewBag.MyMessageToView = "Hello from me.";
and in View, the user can retrieve the value by use the property name as below,
<label>My Message:</label> @ViewBag.MyMessageToView

ViewData

ViewData is similar to ViewBag. It is useful in transferring data from Controller to View. ViewData is a dictionary (ViewDataDictionary) which can contain key-value pairs where each key must be string. You can set and read values to the ViewData dictionary using standard dictionary syntax, as follows:
ViewData["CurrentTime"] = DateTime.Now;

Example,

public ActionResult Index()
{
    IList<Student> studentList = new List<Student>();
    studentList.Add(new Student(){ StudentName = "Bill" });
    studentList.Add(new Student(){ StudentName = "Steve" });
    studentList.Add(new Student(){ StudentName = "Ram" });

    ViewData["students"] = studentList;
  
    return View();
}

In the above example, we have added a student list with the key "students" in the ViewData dictionary. So now, the student list can be accessed in a view as shown below.

<ul>
@foreach (var std in ViewData["students"] as IList<Student>)
{
    <li>
        @std.StudentName
    </li>
}
</ul>

Please notice that we must cast ViewData values to the appropriate data type.

TempData

TempData in ASP.NET MVC can be used to store temporary data which can be used in the subsequent request. TempData will be cleared out after the completion of a subsequent request. TempData is useful when you want to transfer non-sensitive data from one action method to another action method of the same or a different controller as well as redirects. It is dictionary type which is derived from TempDataDictionary. TempData values will be retained during redirection. TempData internally use Session to store the data. So think of it as a short-lived session. You can add a key-value pair in TempData as shown in the below example.

public class HomeController : Controller
{
    // GET: Student
    public HomeController()
    {

    }
    public ActionResult Index()
    {
        TempData["name"] = "Test data";
        TempData["age"] = 30;

        return View();
    }

    public ActionResult About()
    {
        string userName;
        int userAge;
        
        if(TempData.ContainsKey("name"))
            userName = TempData["name"].ToString();
    
        if(TempData.ContainsKey("age"))
            userAge = int.Parse(TempData["age"].ToString());
    
        // do something with userName or userAge here 

        return View();
    }
}
⚠️ **GitHub.com Fallback** ⚠️