Need sample code
Loading
Need sample code
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Cynthia SathuragiriPosted Dec 8, 2025, 4:44 AM
Passing Data Between Controller and View
// ----- CONTROLLER -----
public ActionResult Example()
{
ViewBag.Msg = "From ViewBag";
ViewData["Note"] = "From ViewData";
TempData["Alert"] = "From TempData";
var user = new User { Name = "name", Age = 25 }; // Model
return View(user); // Passing Model to View
}
// ----- VIEW (Example.cshtml) -----
@model YourNamespace.User
@ViewBag.Msg
@ViewData["Note"]
@TempData["Alert"]
Name: @Model.Name
Age: @Model.Age
ViewBag ? Passes data from controller to view for the same request (easy, dynamic).
ViewData ? Same purpose as ViewBag but uses a dictionary format.
TempData ? Keeps data for the next request (useful after redirects).
Model ? Strong, structured data passed to the view (best practice).