Need sample code
Pass Data Between the Controller and View
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Need sample code
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Cynthia SathuragiriRank #937 · 2.2K reputationPosted Dec 7, 2025, 11:44 PM EST
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).