Various Ways to Pass Data from Controller to View in MVC

Introduction

In the MVC pattern, passing data from the controller to the view is essential for dynamic web development. Let's explore different methods to accomplish this in C# MVC.

Methods of Passing Data

1. ViewBag

ViewBag is a dynamic property that allows you to share data between the controller and the view.

2. ViewData

ViewData is a dictionary-like object used to pass data from the controller to the view. It's type-safe and requires typecasting in the view.

3. TempData

TempData is a dictionary with a short life span. It persists for the duration of an HTTP redirect, making it useful for passing data between actions.

4. Model

The preferred way to pass data to a view is through a strongly-typed model. Define a class representing the data and pass an instance of it to the view.

Implementation Examples

ViewBag Example:

<!-- Controller -->
ViewBag.Message = "Hello, ViewBag!";

<!-- View -->
<p>@ViewBag.Message</p>

ViewData Example:

<!-- Controller -->
ViewData["Message"] = "Hello, ViewData!";

<!-- View -->
<p>@ViewData["Message"]</p>

TempData Example:

<!-- Controller -->
TempData["Message"] = "Hello, TempData!";
return RedirectToAction("About");

<!-- Another Action (About) -->
ViewBag.Message = TempData["Message"];

Model Example:

<!-- Model -->
public class MyModel
{
    public string Message { get; set; }
}

<!-- Controller -->
MyModel model = new MyModel { Message = "Hello, Model!" };
return View(model);

<!-- View -->
@model MyModel
<p>@Model.Message</p>

Conclusion

Passing data from the controller to the view is crucial for building dynamic web applications. In C# MVC, you can use ViewBag, ViewData, TempData, or strongly-typed models for this purpose. Each method has its use cases, so choose the one that fits your requirements best.

Related Articles
Coming Soon