Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access viewbag values from view (.cshtml)

Hi Can someone help me how to access viewbag values from my view (.cshtml) Here is my sample

var appointments = new[,] { { "4/1/2013", "B'day" }, { "4/2/2013", "Appointment with abc" } };
ViewBag.Appointments = appointments;

Now I want to access ViewBag.Appointments values from my .cshtml file.

Any idea?

like image 962
jestges Avatar asked Apr 10 '26 23:04

jestges


1 Answers

This is how you are going to access the data in your ViewBag. Remember ViewBag data is normally dynamic and can only be accessed at runtime.

ViewBag.Appointments = appointments;

After you've set ViewBag data in the controller, retrieve it in your view as shown below.

@{
    var appointments = ViewBag.Appointments;
}

Then you can loop through the results to get the individual items using a foreach loop.

@foreach(var appointment in appointments)
{
    <p>@appointment.value</p>
}

Hope this helps!

like image 59
Timothy Macharia Avatar answered Apr 13 '26 23:04

Timothy Macharia