The example below will show you how to assign a value from a ViewBag to a label in ASP.NET MVC. You can replace the label with anything else you wish, like text box, or even am alert box.
In the controller that you are working with, assign the value to the viewBag “Name”. This value will be retried later to show it a label.

First, create a controller, then add the code below to the actionResult Index

        public ActionResult Index()
        {
            ViewBag.Name = "TutorialsPanel";
            return View();

        }

The code above will put the value “TutorialsPanel” in a viewBag that is called “Name”

Now create a view for the controller above, then add the code below to show what’s in the viewBad “Name” in a label:

<h2>The ViewBag contains the value</h2>
@Html.Label("Name", (string)ViewBag.Name)

Now run the application and navigate to the view you created above.

Output:

Related Articles

How Controllers Handle Requests in ASP.NET Core MVC?

C# if statement

Last modified: March 6, 2019

Comments

Write a Reply or Comment

Your email address will not be published.