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.