Menu

How to Pass Data Between Controllers in ASP.NET Core
πŸ–ΌοΈ

How to Pass Data Between Controllers in ASP.NET Core

DEV CommunityΒ·Libin Tom BabyΒ·6 months ago
#B7Vyfc7c
#option#when#limitations#dotnet#session
Reading 0:00
15s threshold

TempData, Session, RouteData, RedirectToAction with params, service-layer approach (the right way)

It's a common scenario: one controller handles a form submission, and you need to pass a message or result to another controller's action after a redirect.

But passing data between controllers is trickier than it looks β€” and most approaches have hidden tradeoffs.

Why You Can't Just Use a Variable

HTTP is stateless.

A redirect from OrderController to DashboardController is a completely new HTTP request. Any variables you set in the first request are gone by the time the second request arrives.

You need a mechanism to persist data across that boundary.

Option 1: TempData

TempData is a dictionary that persists for exactly one redirect β€” cleared after the next request reads it.

// OrderController.cs [ HttpPost ] public IActionResult Create ( CreateOrderDto dto ) { var orderId = _orderService . Create ( dto ); TempData [ "SuccessMessage" ] = "Order created successfully!" ; TempData [ "OrderId" ] = orderId .…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.