Data Sharing Techniques In MVC

1) View Data

ViewData is a built-in object of the "ViewDataDictionary" class.

ViewData stores the data in key-value pairs

Example

public IActionResult Index() {
    ViewData["Name"] = "MVC";
    return View();
}

Output

2) View Bag

ViewBag is also used for sending Data from the controller to View.

ViewBag is developed based on Dynamic Typing.

No need to perform Type Casting

Use key as property

Example

public IActionResult ViewBagIndex() {
    ViewBag.Name = "MVC";
    return View();
}

Output

3) Temp Data

TempData is used to transfer the aata from one Action to Another Action at the time of redirection

TempData is an object of the "TempDataDictionary" class

Example

public ActionResult TempDataIndex() {
    TempData["Name"] = "MVC";
    return View();
}

Output

Please do leave a comment if you find it useful. You can find the repository here.


Similar Articles