ASP.NET ViewBag
last modified October 18, 2023
In this article we show how to pass data betweeen controllers and views in ASP.NET with ViewBag.
ASP.NET is a cross-platform, high-performance, open-source framework for building modern, cloud-enabled, web applications. It is developed by Microsoft.
A controller is a class which handles an HTTP request sent from a client. It retrieves model data and returns a response back to the client. A view displays data and handles user interaction.
A ViewBag is a controller property which is used to pass data from controllers to views. It is used for passing weakly-typed data. ViewBag is suitable for passing small amounts of data in and out of controllers and views.
If we want to pass strongly-typed data, we can use viewmodel.
ASP.NET ViewBag example
In the following example, we show how to use ViewBag.
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllersWithViews(); var app = builder.Build(); app.UseRouting(); app.UseEndpoints(endppoints => { endppoints.MapDefaultControllerRoute(); }); app.Run("http://localhost:3000");
We set up controllers and views.
using Microsoft.AspNetCore.Mvc; namespace ViewBagEx.Controllers; public class HomeController : Controller { public IActionResult Index() { ViewBag.Now = DateTime.Now; return View(); } [HttpGet("words")] public IActionResult Words() { var words = new List<string> { "red", "class", "rock", "war" }; ViewBag.Words = words; return View(); } }
In the controller we have two actions. The first returns the current datetime and the second a list of words.
ViewBag.Now = DateTime.Now;
We set the current datetime to the ViewBag.
var words = new List<string> { "red", "class", "rock", "war" }; ViewBag.Words = words;
Here we set a list of strings.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home page</title> </head> <body> <p> @ViewBag.Now </p> </body> </html>
In this view we display the current datetime. We access the bag via
@ViewBag
.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Words</title> </head> <body> <ul> @{ foreach (var word in ViewBag.Words) { <li>@word</li> } } </ul> </body> </html>
In this view, we display the words in an HTML list. We go through the list of words in a foreach loop.
$ dotnet watch
We start the application and navigate to localhost:3000
and localhost:3000/words
.
In this article we have shown how to pass data betweeen controllers and views with ViewBag.