Site icon Tutexchange

Understanding ViewBag in ASP.NET Core MVC

Advertisements

In this article, we will explore how to use ViewBag in an ASP.NET Core 3.0 MVC application to pass data from a controller to a view. ViewBag is a dynamic object that provides a simple way to transfer temporary data without the need for strongly typed models.

What is ViewBag?

When to Use ViewBag

Use ViewBag when:

Avoid using ViewBag for large or complex data models. Use ViewModel or ViewData in such cases.

Step-by-Step Example

Step 1: Create a Controller

We are going add Controller with Name Demo3 with Index action method inside that we are going to declare ViewBag with a string value.

using Microsoft.AspNetCore.Mvc;

namespace WebApplication2.Controllers
{
    public class Demo3Controller : Controller
    {
        public IActionResult Index()
        {
            ViewBag.Message = "Hi Message";
            return View();
        }
    }
}

Step 2: Create a View

<h1>Index</h1>

Message:- @ViewBag.Message

Read more :- https://tutexchange.com/quick-view-at-developer-features-of-bugpoint-application/

Read more:- https://learn.microsoft.com/en-us/answers/questions/796983/viewbag-in-asp-net-core

Exit mobile version