简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM