I have a List in the controller
List<string> myList = new List<string>(); myList.Add(aString); ViewBag.linkList = myList;
And then in the View I am trying to do
@ViewBag.linkList.First()
And it is giving me the error: 'System.Collections.Generic.List' does not contain a definition for 'First'
If I do
@ViewBag.linkList[0]
It works fine.
I already put @using System.Linq
in the view. Am I missing something? Does Linq works inside the view?
ViewBag
is dynamic. First()
is an extension method on IEnumerable<T>
. Extension methods don't work on dynamic references.
You must first cast your list to IEnumerable<string>
before calling First()
.
@((ViewBag.linkList as IEnumerable<string>).First())
Note that plain IEnumerable
will not work, since .First()
is not defined for it.
Try casting it to IEnumerable<T>
, like this:
@((IEnumerable<string>)ViewBag).linkList.First()
or to List<string>
:
@((List<string>)ViewBag).linkList.First()
The ViewBag is a dynamic
object... More specifically, an ExpandoObject
. I'm guessing that the dynamic binder is having difficulty identifying the original type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With