Final Form
Final Form

Reputation: 318

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?

Upvotes: 7

Views: 1081

Answers (3)

Nick
Nick

Reputation: 1122

You should pass the list into the view via a ViewModel. In its simplest form pass the list ino the View from the controller eg. return View(myList);

In the view add @model = List<string> at the top of the page. You can then use Model.First() model.First() to get the item you want.

ViewModels can be created as classes or structs, or jut simple data types, however the benefit is they are strongly typed when they get into the View.

Upvotes: 1

recursive
recursive

Reputation: 86064

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.

Upvotes: 8

Robert Harvey
Robert Harvey

Reputation: 180777

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.

Upvotes: 2

Related Questions