问题
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?
回答1:
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.
回答2:
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
}
来源:https://stackoverflow.com/questions/41577090/how-to-check-if-a-list-in-a-viewbag-contains-string