Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq doesn't work in MVC View

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?

like image 344
Final Form Avatar asked Aug 01 '13 00:08

Final Form


2 Answers

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.

like image 187
recursive Avatar answered Sep 21 '22 07:09

recursive


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.

like image 38
Robert Harvey Avatar answered Sep 21 '22 07:09

Robert Harvey