简体   繁体   中英

How to check if a List in a ViewBag contains string

I have a ViewBag that is a list which i create in the controller:

 List<string> listoflists = new List<string>();

it then gets filled with some string like for example:

listoflists.Add("java");
listoflists.Add("php");
listoflists.Add("C#");

Adding it to the ViewBag: ViewBag.listoflists = listoflists;

i then would like to check in my View if this contains a specific string:

@if(ViewBag.listoflists.contains("java")
{
// do html stuff
}

but when running this i get the following error:

System.Collections.Generic.List does not contain a definition for contains

What am i doing wrong, or how should i check if a list contains something in the View?

You might need to cast back to a list of strings:

@if (((IList<string>)ViewBag.listoflists).Contains("java")
{
    // do html stuff
}

Also notice that the Contains method starts with a capital C .

So as you can see using ViewBag in ASP.NET MVC is a complete crap leading to very ugly code in your views. For this reason it is strongly recommended to use view models which will contain all the necessary information of a specific view and also being strongly typed.

So cut this ViewBag crap and start using view models:

public class MyViewModel
{
    public IList<string> ListOfLists { get; set; }
}

that your controller action can populate and pass to the view:

public ActionResult Index()
{
    var model = new MyViewModel();
    List<string> listoflists = new List<string>();
    listoflists.Add("java");
    listoflists.Add("php");
    listoflists.Add("C#");
    model.ListOfLists = listoflists;
    return View(model);
}

and now you can have a strongly typed view to this model which will allow you to avoid the previous casting:

@model MyViewModel

@if (Model.ListOfLists.Contains("java"))
{
    // do html stuff
}

So basically every time you use ViewBag/ViewData in an ASP.NET MVC application an alarm should immediately ring in your head telling you: Man, what the hell, you are doing it wrong. Just use a view model in order to avoid transforming your views into an abominable mess of completely irrelevant C# language constructs like casting and stuff. Views are meant for displaying markup.

ViewBag is a dynamic type, it does not know at compile time what is the actual type contained in the key ViewBag.listoflists you defined, you need to cast it to specific type and then you can call those methods on it:

@{

List<string> languages= ViewBag.listoflists as List<string>;
}
@if(languages.contains("java")
{
// do html stuff
}

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