In my ASP.NET MVC View, I want to loop through Viewbag.A
to ViewBag.Z
but I’m not sure how to do this.
This is what I have in my view:
@{
for (char letter = 'A'; letter <= 'Z'; letter++)
{
<h1 id=@letter>@letter</h1>
if (ViewBag.@letter != null)
{
foreach (var item in ViewBag.@letter))
{
// do something here
}
}
}
}
Is there a way to use a variable such as @letter
in ViewBag
name?
4
Answers
Thank you David for the clue. I stored all the values in a single ViewBag. Then in the view, I used StartsWith() to filter the results as below
}
Thank you all.
Try this code man
You can use reflection to enumerate the internal
ViewDataDictionary
of theViewBag
:I think better way to get your result would be to have a dictionary containing your ViewBag items and iterating through them that way, so your code would look something like this:
And then your razor script will look something like this: