Methods to Pass Data from Controller to View
ViewBag:
A dynamic property that allows you to pass data to the view.
Example:
public ActionResult Index()
{
ViewBag.Message = "Hello from ViewBag!";
return View();
}
Access in View:
<h1>@ViewBag.Message</h1>
ViewData:
A dictionary-like object that stores data as key-value pairs.
Example:
public ActionResult Index()
{
ViewData["Message"] = "Hello from ViewData!";
return View();
}
Access in View:
<h1>@ViewData["Message"]</h1>
Strongly-Typed Views:
Pass a model object to the view.
Example:
public ActionResult Index()
{
var model = new MyModel { Message = "Hello from Model!" };
return View(model);
}
Access in View (declare the model at the top of the view):
@model MyNamespace.MyModel
<h1>@Model.Message</h1>