如何检查ViewBag中的列表是否包含字符串 [英] How to check if a List in a ViewBag contains string
问题描述
我有一个ViewBag,它是我在控制器中创建的列表:
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#");
将其添加到ViewBag中:
ViewBag.listoflists = listoflists;
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不包含包含的定义
我在做什么错了,还是应该检查列表中是否包含某些内容?
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
}
还请注意,包含
方法以大写字母 C
。
Also notice that the Contains
method starts with a capital C
.
因此您可以看到在A中使用ViewBag SP.NET MVC是一个完整的废话,导致您的视图中的代码非常丑陋。因此,强烈建议使用视图模型,该模型将包含特定视图的所有必要信息,并且也应进行强类型输入。
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.
因此,请切下 ViewBag
废话并开始使用视图模型:
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
}
因此,基本上,每次您在ASP.NET MVC应用程序中使用ViewBag / ViewData时,都会立即响起警报,告诉您:伙计,这到底是什么,您做错了。只需使用视图模型即可避免将视图转换为完全不相关的C#语言构造(如转换和填充)的可恶的混乱。视图用于显示标记。
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中的列表是否包含字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!